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. Each call gave you back one Future. That works well, but real programs often have a whole batch of tasks. You might need to load ten files, ask three servers for the same data, or add up the results of many small calculations.
Java gives you two methods for working with a batch of tasks:
invokeAllruns every task in a list and waits until all of them are done.invokeAnyruns every task in a list and gives you the result of the first one that finishes without an error.
This chapter shows how each method works, what it returns, and what happens when tasks fail or take too long.
What "batch submission" means
Batch submission means giving the executor a whole collection of tasks in one call instead of looping over submit yourself. The collection must hold Callable objects. A Callable is a task that returns a value and is allowed to throw an exception. You met it in the chapter on Callable and Future.
Both methods are blocking. A blocking method makes the calling thread stop and wait until the method has an answer. With invokeAll, your thread waits for every task. With invokeAny, your thread waits for one successful task.
invokeAll: run everything, collect everything
invokeAll takes a collection of Callable tasks and returns a List<Future<T>>. The list has these properties:
- It has one
Futurefor each task. - The futures are in the same order as the tasks in your input list. The first future belongs to the first task, and so on. This holds even if the tasks finished in a different order.
- Every future is already done when
invokeAllreturns. Callingget()on one of them returns right away without waiting.
Here is a small example that adds up the results of three tasks.
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();
}
}
}Output:
Sum: 6Step by step:
List.of(() -> 1, () -> 2, () -> 3)builds a list of three lambdas. Java treats each lambda as aCallable<Integer>because the variable type says so.pool.invokeAll(tasks)hands all three tasks to the pool. The pool has three threads, so the tasks can run at the same time.- The main thread waits inside
invokeAlluntil all three tasks are finished. - The loop reads each future with
get()and adds the value tosum. - The
finallyblock shuts the pool down, as you learned in the shutdown chapter.
When one task in the batch fails
"Done" does not mean "succeeded." A task counts as done when it returns a value, throws an exception, or gets cancelled. invokeAll does not throw just because one task failed. It still waits for the others and returns all the futures.
You find out about a failure when you call get() on that task's future. As the previous chapter showed, get() wraps the task's exception in an ExecutionException. Catch it for each future so that one bad task does not hide the good results.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class InvokeAllFailureDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(3);
try {
List<Callable<Integer>> tasks = List.of(
() -> 10,
() -> Integer.parseInt("oops"),
() -> 30);
List<Future<Integer>> futures = pool.invokeAll(tasks);
for (int i = 0; i < futures.size(); i++) {
try {
System.out.println("Task " + i + ": " + futures.get(i).get());
} catch (ExecutionException e) {
System.out.println("Task " + i + " failed: " + e.getCause());
}
}
} finally {
pool.shutdown();
}
}
}Output:
Task 0: 10
Task 1 failed: java.lang.NumberFormatException: For input string: "oops"
Task 2: 30The try/catch sits inside the loop. If it were outside, the first failure would stop the loop and you would never print the result of task 2.
Putting a time limit on invokeAll
Sometimes you cannot wait forever. invokeAll has a second version that takes a timeout:
List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)If the time runs out, the executor cancels every task that has not finished yet. A cancelled task's future reports isCancelled() as true. Calling get() on it throws a CancellationException, so check isCancelled() first.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class InvokeAllTimeoutDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
List<Callable<String>> tasks = List.of(
() -> "quick",
() -> { Thread.sleep(5_000); return "slow"; });
List<Future<String>> futures = pool.invokeAll(tasks, 1, TimeUnit.SECONDS);
for (Future<String> f : futures) {
if (f.isCancelled()) {
System.out.println("Timed out and cancelled");
} else {
System.out.println("Result: " + f.get());
}
}
} finally {
pool.shutdown();
}
}
}Output, after about one second:
Result: quick
Timed out and cancelledinvokeAny: the first success wins
invokeAny also takes a collection of Callable tasks, but it returns a single value, not a list of futures. That value comes from one task that finished successfully, meaning without throwing. Once it has a winner, the executor cancels the tasks that are still running.
This is useful when several tasks can each give you the same answer and you only need one. A common case is asking three copies of a server (called mirrors) for the same file and using whichever replies 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("Winner: " + winner);
} finally {
pool.shutdown();
}
}
}Output, almost always:
Winner: fast mirrorThe sleeps only pretend to be network calls of different speeds. The 100 ms task usually finishes first, so its value is returned. The other two tasks are cancelled. That interrupts their Thread.sleep, so they stop early.
When tasks fail in invokeAny
Failed tasks are skipped. If a task throws, invokeAny keeps waiting for another one to succeed. Only when every task has failed does invokeAny throw an ExecutionException. Its cause is the exception from one of the failed tasks.
invokeAny also has a timeout version. If no task succeeds in time, it throws a TimeoutException.
Choosing between them
| Question | invokeAll | invokeAny |
|---|---|---|
| What does it return? | `List<Future<T>>`, one per task | One value of type `T` |
| When does it return? | When every task is done | When one task succeeds |
| What about the other tasks? | All run to the end | Unfinished ones are cancelled |
| One task throws | Shows up later in that future's `get()` | Ignored if another task succeeds |
| Every task throws | Each `get()` throws `ExecutionException` | `invokeAny` throws `ExecutionException` |
| Timeout version runs out | Unfinished tasks cancelled, list still returned | Throws `TimeoutException` |
| Typical use | Need every result, like summing parts | Need any one answer, like fastest mirror |
Common mistakes
- Passing
Runnabletasks. Both methods only acceptCallable. A lambda that returns nothing, such as() -> System.out.println("hi"), does not compile here. Add a return value or wrap the work in aCallable. - Using a pool that is too small. With a pool of one thread, the tasks run one after another.
invokeAllstill works, just slowly.invokeAnyloses most of its benefit because tasks cannot race each other. - One
try/catcharound the whole loop. The first failed future then hides all the results after it. CatchExecutionExceptionfor each future. - Forgetting to shut down. Batch methods do not shut down the pool for you. Keep the
finally { pool.shutdown(); }pattern.
Exercise
You call invokeAll with four tasks. Task 3 throws an IllegalStateException and the others return normally. Does invokeAll itself throw? How do you find out about the failure?
Show answer
No. invokeAll waits until all four tasks are done and returns four futures in input order. The failure appears only when you call get() on the third future, which throws an ExecutionException whose getCause() is the IllegalStateException.
Exercise
Write a Callable list for invokeAny where the first task throws a RuntimeException right away and the second task sleeps 200 ms and then returns "backup". What does invokeAny return?
Show answer
It returns "backup". invokeAny skips tasks that fail and waits for one that succeeds. Example list: List<Callable<String>> tasks = List.of(() -> { throw new RuntimeException("down"); }, () -> { Thread.sleep(200); return "backup"; });
Exercise
You use invokeAll(tasks, 2, TimeUnit.SECONDS) and one task needs 10 seconds. What happens to that task, and how should your loop check its future before calling get()?
Show answer
After 2 seconds the executor cancels the unfinished task. Its future returns true from isCancelled(), and calling get() on it would throw a CancellationException. Check f.isCancelled() first and only call get() when it returns false.