CompletableFuture.allOf: Waiting for All Tasks
What you'll learn: How to use CompletableFuture.allOf to coordinate multiple asynchronous tasks and wait for all of them to complete.
The Coordination Challenge
When you have several independent asynchronous operations running simultaneously, you often need to wait for all of them to finish before proceeding. Think of it like organizing a group dinner—you can't start the meal until everyone has arrived.
Understanding allOf
CompletableFuture.allOf is a static factory method that creates a new CompletableFuture which completes when all the input futures complete. Here's its signature:
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
Key characteristics:
- Varargs parameter: Accepts any number of
CompletableFutureinstances - Return type:
CompletableFuture<Void>— it doesn't provide combined results, only signals completion - Completion trigger: The returned future completes when all input futures complete (successfully or exceptionally)
How It Works
When you call allOf, you're creating a coordination point:
CompletableFuture<String> task1 = supplyAsync(() -> "Result 1");
CompletableFuture<Integer> task2 = supplyAsync(() -> 42);
CompletableFuture<Boolean> task3 = supplyAsync(() -> true);
CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2, task3);
The allTasks future completes only after task1, task2, and task3 all finish. Notice the futures can have different type parameters—allOf doesn't care about the result types, only about completion status.
The Void Return Type
Since allOf returns CompletableFuture<Void>, it doesn't provide access to individual results directly. You must retrieve results from the original futures after allOf completes.
Key Takeaway: CompletableFuture.allOf creates a synchronization point that completes when all input futures complete, returning CompletableFuture<Void> to signal collective completion without combining results.