JAVA
Java ExecutorService – invokeAll() vs invokeAny()
neal89
2025. 3. 25. 13:18
✅ invokeAll(): Wait for All Tasks to Complete
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
🔹 What it does:
- Submits all tasks at once
- Waits until every task finishes
- Returns a list of Future<T> objects, each representing the result of one task
⏱ With timeout:
invokeAll(tasks, timeout, timeUnit)
- Waits for all tasks, but only within the given time limit
💡 Example – invokeAll()
ExecutorService executor = Executors.newFixedThreadPool(10);
List<CallableTask> tasks = List.of(
new CallableTask("task1", 1000),
new CallableTask("task2", 2000),
new CallableTask("task3", 3000)
);
List<Future<Integer>> futures = executor.invokeAll(tasks);
for (Future<Integer> future : futures) {
Integer result = future.get();
System.out.println("Result: " + result);
}
executor.shutdown();
✅ Output (parallel execution):
task1 running
task2 running
task3 running
task1 done → return 1000
task2 done → return 2000
task3 done → return 3000
Result: 1000
Result: 2000
Result: 3000
🧠 Use invokeAll() when you need all results and are willing to wait.
✅ invokeAny(): Return First Completed Result
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
🔹 What it does:
- Submits all tasks
- Waits only for the first successful result
- Cancels the remaining tasks
⏱ With timeout:
invokeAny(tasks, timeout, timeUnit)
- Waits for the fastest task to finish within the time limit, otherwise throws TimeoutException
💡 Example – invokeAny()
ExecutorService executor = Executors.newFixedThreadPool(10);
List<CallableTask> tasks = List.of(
new CallableTask("task1", 1000),
new CallableTask("task2", 2000),
new CallableTask("task3", 3000)
);
Integer result = executor.invokeAny(tasks);
System.out.println("First result: " + result);
executor.shutdown();
✅ Output:
task1 running
task2 running
task3 running
task1 done → return 1000
First result: 1000
task2 interrupted
task3 interrupted
🧠 Use invokeAny() when you only care about the fastest result, and want to save resources by cancelling the others.
🔄 Summary – invokeAll() vs invokeAny()
Feature invokeAll() invokeAny()
Waits for all tasks | ✅ Yes | ❌ No – only waits for one |
Cancels others | ❌ No | ✅ Yes – cancels remaining tasks |
Return value | List of Future<T> | Single T |
Use case | Need all results | Need fastest result |