Using allOf with Varargs
You'll learn how to pass multiple CompletableFuture instances to allOf() using Java's varargs syntax.
The Varargs Parameter
The allOf() method accepts its futures through a varargs parameter, which means you can pass any number of CompletableFuture arguments directly without needing to create an array explicitly.
The signature looks like this:
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs)
The ... syntax indicates varargs—you can pass zero or more futures as separate arguments.
Passing Multiple Futures
You have two ways to provide futures to allOf():
1. Direct varargs syntax (most common):
CompletableFuture<String> future1 = supplyAsync(() -> "Task 1");
CompletableFuture<Integer> future2 = supplyAsync(() -> 42);
CompletableFuture<Boolean> future3 = supplyAsync(() -> true);
CompletableFuture<Void> all = CompletableFuture.allOf(future1, future2, future3);
2. Explicit array syntax:
CompletableFuture<?>[] futuresArray = {future1, future2, future3};
CompletableFuture<Void> all = CompletableFuture.allOf(futuresArray);
Why Varargs Matters
The varargs parameter type CompletableFuture<?>... accepts futures with any result type. Notice how future1 returns String, future2 returns Integer, and future3 returns Boolean—all different types. The wildcard <?> allows this flexibility.
This is why allOf() returns CompletableFuture<Void> rather than a typed result—there's no single type that encompasses all the different futures you might pass.
Practical Flexibility
The varargs approach makes coordination intuitive. Whether you have 2 futures or 20, you simply list them as arguments without extra ceremony.
Key Takeaway: allOf() uses varargs (CompletableFuture<?>...) to accept any number of futures with different result types, making it flexible and easy to coordinate multiple asynchronous operations.