Error Handling with allOf
What you'll learn: How exceptions in any input future cause allOf to complete exceptionally and practical strategies for recovering from such failures.
The Fail-Fast Nature of allOf
When you use CompletableFuture.allOf(), you're waiting for all futures to complete. However, if any single future completes exceptionally, the entire allOf future also completes exceptionally immediately. Think of it like a relay race: if one runner falls, the whole team is disqualified on the spot.
This fail-fast behavior means you need explicit strategies to handle failures gracefully.
The Challenge
Since allOf returns CompletableFuture<Void>, you can't directly access individual results or errors from the input futures. The exception you'll catch is from whichever future failed first, but other futures may also have failed (or might still be running).
Recovery Strategies
Strategy 1: Use exceptionally or handle on allOf itself
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2, future3)
.exceptionally(ex -> {
System.err.println("One or more futures failed: " + ex.getMessage());
return null; // Return Void
});
Strategy 2: Check each future individually after allOf
CompletableFuture.allOf(future1, future2, future3)
.handle((result, ex) -> {
if (ex != null) {
// Examine each future to see which failed
if (future1.isCompletedExceptionally()) {
// Handle future1 failure
}
if (future2.isCompletedExceptionally()) {
// Handle future2 failure
}
// etc.
}
return null;
});
Key Takeaway: allOf fails immediately when any input future fails; use exceptionally or handle to recover, and inspect individual futures to identify specific failures when needed.