Course contentsShow
← Java
Lesson 2762 of 2,87050. Executor FrameworkFree lesson

Handling Exceptions with invokeAll

Understand that invokeAll never throws ExecutionException directly; exceptions are retrieved when calling Future.get().

Handling Exceptions with invokeAll

You'll learn how invokeAll handles task failures differently from single-task submission methods.

When you submit multiple tasks using invokeAll, the method itself never throws ExecutionException directly. This is a critical distinction from calling submit() and immediately calling get() on the result. Instead, invokeAll returns a list of Future objects regardless of whether the tasks succeeded or failed during execution.

Where Exceptions Actually Surface

The exceptions thrown by your Callable tasks are encapsulated inside the returned Future objects. They only surface when you call Future.get() on each individual future. At that point, if the corresponding task threw an exception, get() will wrap it in an ExecutionException and throw it to you.

This design means invokeAll acts as a "collect all futures" operation rather than a "wait for all successes" operation. It blocks until all tasks complete (successfully or not), then hands you the futures to inspect individually.

Practical Implication

Think of invokeAll like a mail carrier who delivers all packages to your door, regardless of whether some are damaged. The carrier doesn't open the packages—that's your job. Similarly, invokeAll delivers all Future objects without checking their contents. You must call get() on each to discover which tasks succeeded and which failed.

List<Future<Integer>> futures = executor.invokeAll(tasks);

for (Future<Integer> future : futures) {
    try {
        Integer result = future.get(); // Exception surfaces HERE
        // Process successful result
    } catch (ExecutionException e) {
        // Handle the wrapped task exception
        Throwable cause = e.getCause();
    }
}

Key Takeaway:
invokeAll never throws ExecutionException itself; it returns all futures immediately after completion, and exceptions are only thrown when you call get() on individual futures.