invokeAny: Racing Multiple Callables
You'll learn how invokeAny executes multiple tasks concurrently and returns the result of the first one to complete successfully.
The Concept: A Race to Completion
While invokeAll waits for all tasks to finish, invokeAny takes a different approach—it runs multiple Callable tasks simultaneously and returns as soon as any one succeeds. The remaining tasks are cancelled automatically.
Think of it like ordering the same item from multiple suppliers: whoever delivers first wins, and you cancel the other orders.
How invokeAny Works
ExecutorService executor = Executors.newFixedThreadPool(3);
Collection<Callable<String>> tasks = Arrays.asList(
() -> {
Thread.sleep(2000);
return "Task 1 completed";
},
() -> {
Thread.sleep(500);
return "Task 2 completed (fastest!)";
},
() -> {
Thread.sleep(1500);
return "Task 3 completed";
}
);
try {
String result = executor.invokeAny(tasks);
System.out.println(result); // "Task 2 completed (fastest!)"
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
Key Behavior Points
Returns immediately after first success: Unlike invokeAll which returns all Future objects, invokeAny returns the actual result directly—no Future.get() needed.
Cancels remaining tasks: Once a task succeeds, the executor attempts to cancel the others to avoid wasting resources.
Throws if all fail: If every task throws an exception, invokeAny throws ExecutionException wrapping the last exception encountered.
Common Use Cases
This pattern shines when you have multiple ways to compute the same result (redundant servers, alternative algorithms) and want the fastest available answer.
Key Takeaway: invokeAny races multiple Callable tasks concurrently and returns the first successful result, automatically cancelling the rest—perfect for redundant computations where speed matters.