Sub topic 10
Running Many Tasks at Once with invokeAll and invokeAny
So far you have handed tasks to an ExecutorService one at a time with submit. Sometimes you have a whole batch of tasks instead. You might want every result, or you might want only the first good one. Java gives you two methods for these cases: invokeAll and invokeAny.
What Batch Submission Means
Batch submission means you give the pool a list of tasks in one call. Each task is a Callable, which is a task that returns a value. The pool runs the tasks on its threads at the same time, as far as it has free threads.
Both methods are blocking. A blocking method makes the calling thread wait until the method is done. Your main thread pauses on the call and moves on only when the answer is ready.
| Method | What it waits for | What it returns |
|---|---|---|
| `invokeAll` | Every task to finish | A `List` of `Future` objects, one per task |
| `invokeAny` | One task to finish without an error | The plain result of that one task |
invokeAll: Wait for Every Task
invokeAll takes a list of Callable tasks. It returns a list of Future objects. A Future holds the result of a task. The list comes back in the same order as your task list. The first Future belongs to the first task, even if that task finished last.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class InvokeAllDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
List<Callable<Integer>> tasks = List.of(() -> 1, () -> 2, () -> 3);
int sum = 0;
for (Future<Integer> f : pool.invokeAll(tasks)) {
sum += f.get();
}
System.out.println("Sum: " + sum);
} finally {
pool.shutdown();
}
}
}This prints Sum: 6. By the time invokeAll returns, every task is done. So f.get() does not wait here. It just reads the stored result.
invokeAny: Take the First Success
invokeAny also takes a list of Callable tasks. It returns the result of the first task that finishes without throwing. Then it cancels the other tasks, because you no longer need them.
This helps when several sources can give the same answer. One example is asking three mirror servers for the same file and keeping whichever answers first.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class InvokeAnyDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
List<Callable<String>> mirrors = List.of(
() -> { Thread.sleep(300); return "slow mirror"; },
() -> { Thread.sleep(100); return "fast mirror"; },
() -> { Thread.sleep(200); return "medium mirror"; });
String winner = pool.invokeAny(mirrors);
System.out.println("First answer: " + winner);
} finally {
pool.shutdown();
}
}
}This usually prints First answer: fast mirror. The two slower tasks get cancelled while they sleep. If every task fails, invokeAny throws an ExecutionException.
Common Mistakes
- Expecting results in finishing order.
invokeAllkeeps your input order. It does not sort by speed. - Forgetting it blocks. Both calls pause the calling thread. Do not call them where you cannot afford to wait.
- Waiting forever. Both methods have versions that take a timeout, such as
invokeAll(tasks, 5, TimeUnit.SECONDS). When the time runs out,invokeAllcancels any unfinished tasks, andinvokeAnythrows aTimeoutException.
Exercise
You have five Callable tasks that each check the weather from a different website. You only need one forecast, as fast as possible. Which method should you use, and what happens to the other four tasks?
Show answer
Use invokeAny. It returns the forecast from the first task that finishes without an error, and it cancels the tasks that have not finished yet.
Exercise
You call invokeAll on tasks [A, B, C]. Task C finishes first and task A finishes last. Which task's result is in the first Future of the returned list?
Show answer
Task A's. invokeAll returns the Futures in the same order as the input list, no matter which task finished first.