Collecting Results After allOf
What you'll learn: How to gather individual results from multiple CompletableFutures after allOf() completes.
The Challenge with allOf
You've learned that CompletableFuture.allOf() returns a CompletableFuture<Void> that completes when all input futures finish. But what if you actually need the results from those futures? The allOf() method doesn't provide them directly—it only signals completion. You must manually collect the results yourself.
The Collection Pattern
After allOf() completes, all the original futures are guaranteed to be done (successfully or exceptionally). You can safely call join() on each future to extract its result without blocking, since the computation is already complete.
The typical pattern involves:
- Creating your array or list of CompletableFutures
- Passing them to
allOf() - Using
thenApply()or similar to transform theVoidresult into collected data - Calling
join()on each original future to gather results
Think of it like waiting for all your friends to finish a race (allOf), then walking around to each friend afterward to ask their individual times (join() on each).
Basic Example Pattern
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Result1");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Result2");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "Result3");
CompletableFuture<Void> allDone = CompletableFuture.allOf(future1, future2, future3);
CompletableFuture<String> combined = allDone.thenApply(v -> {
String r1 = future1.join(); // Safe: already completed
String r2 = future2.join();
String r3 = future3.join();
return r1 + ", " + r2 + ", " + r3;
});
Since allOf() completed, all three futures are done, making join() return immediately with the computed values.
Key Takeaway: After allOf() completes successfully, use join() on the original futures to collect results without blocking—all computations are guaranteed finished.