Course contentsShow
← Java
Lesson 2857 of 2,87051. CompletableFutureFree lesson

Collecting Results After allOf

Learn patterns for gathering results from multiple futures using join() after allOf completes successfully.

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:

  1. Creating your array or list of CompletableFutures
  2. Passing them to allOf()
  3. Using thenApply() or similar to transform the Void result into collected data
  4. 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.