invokeAny with Timeout
You'll learn how to race multiple tasks with a time limit, getting either the fastest result or a timeout exception.
The Core Idea
While invokeAny races tasks and returns the first successful result, the timeout variant adds a crucial constraint: all competing tasks must complete within a specified time limit. If no task finishes successfully before the timeout expires, you get a TimeoutException instead of waiting forever.
Think of it like a cooking competition where contestants race to finish a dish, but there's also a strict time limit. If nobody completes their dish before the buzzer, the competition ends with no winner—even if someone was close.
The Method Signature
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout,
TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException
The key difference: two additional parameters define your patience threshold.
How It Works
When you call invokeAny with a timeout:
- All tasks begin executing concurrently
- The executor waits up to the specified duration
- If any task completes successfully within that window, it returns immediately
- If the timeout expires first,
TimeoutExceptionis thrown - Remaining tasks are cancelled
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Callable<String>> tasks = Arrays.asList(
() -> { Thread.sleep(1000); return "Task 1"; },
() -> { Thread.sleep(5000); return "Task 2"; },
() -> { Thread.sleep(200); return "Task 3"; }
);
try {
String result = executor.invokeAny(tasks, 2, TimeUnit.SECONDS);
// Returns "Task 3" since it completes in 200ms
} catch (TimeoutException e) {
// Would throw if timeout was 100ms instead
}
Key Takeaway: The timeout variant of invokeAny lets you race tasks with a deadline, throwing TimeoutException if none succeed within the limit—essential for preventing indefinite waits in time-sensitive operations.