Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Future.get()

Waits for a task to finish and returns its result.

Available since: Java 1.5

Syntax

V get() throws InterruptedException, ExecutionException
V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

Parameters

ParameterTypeDescription
timeoutlongOptional wait limit.
unitTimeUnitThe time unit of `timeout`.

Return value

VThe task result.

Examples

A result and an exception from a task:

void main() throws InterruptedException {
    try (var pool = Executors.newFixedThreadPool(2)) {
        Future<Integer> ok = pool.submit(() -> 6 * 7);
        Future<Integer> bad = pool.submit(() -> Integer.parseInt("x"));
        try {
            IO.println(ok.get());
            IO.println(bad.get());
        } catch (ExecutionException e) {
            IO.println("task failed: " + e.getCause());
        }
    }
}

Output:

42
task failed: java.lang.NumberFormatException: For input string: "x"

Notes

get() blocks the thread until the result is ready. An exception from the task arrives wrapped in ExecutionException, and the original is available via getCause(). The timeout version throws TimeoutException if the task is too slow.

See also

Related recipes

In the tutorial

  • Thread pools and ExecutorService — ExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.

Thanks for reading!

Donate to the site — we work hard for you.