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, TimeoutExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| timeout | long | Optional wait limit. |
| unit | TimeUnit | The 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
- ExecutorService.submit() — Sends a task to the pool and immediately returns a `Future` for its result.
- CompletableFuture.join() — Waits for the result of a `CompletableFuture`; errors arrive as unchecked exceptions.
- Thread.join() — Waits for a thread to finish.
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.