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

Why allOf Returns CompletableFuture<Void>

Understand why allOf cannot return a typed result and how to retrieve individual future results after completion.

Why allOf Returns CompletableFuture<Void>

You'll learn: Why CompletableFuture.allOf() can't return typed results and how to extract individual future values after coordination.

The Type Problem

When you call allOf(), you're coordinating multiple CompletableFuture instances that may have different result types. Consider:

CompletableFuture<String> future1 = supplyAsync(() -> "Hello");
CompletableFuture<Integer> future2 = supplyAsync(() -> 42);
CompletableFuture<Boolean> future3 = supplyAsync(() -> true);

CompletableFuture<Void> allDone = CompletableFuture.allOf(future1, future2, future3);

What type could allOf possibly return? A String? An Integer? There's no single type that encompasses all results, so Java returns CompletableFuture<Void> — it signals completion without carrying a value.

Think of It as a Coordination Signal

allOf is like a race official's flag: it waves when all runners cross the finish line, but it doesn't carry each runner's time. The times still exist; you just have to check each runner individually.

Retrieving Individual Results

After allOf completes, the original futures hold your results:

CompletableFuture<Void> allDone = CompletableFuture.allOf(future1, future2, future3);

allDone.thenRun(() -> {
    String result1 = future1.join();  // Safe: we know it's complete
    Integer result2 = future2.join();
    Boolean result3 = future3.join();
    
    System.out.println(result1 + ", " + result2 + ", " + result3);
});

Once allDone completes, you're guaranteed that future1, future2, and future3 have all finished, making join() calls safe and non-blocking.

Why Not Return a Collection?

Even if allOf returned a List<Object>, you'd lose type safety and still need casting. The current design keeps the original futures strongly typed while providing a clean coordination point.

Key Takeaway: allOf returns CompletableFuture<Void> because it coordinates heterogeneous futures; retrieve individual results by calling join() on the original futures after allOf completes.