Java CompletableFuture allOf: Wait for Multiple Futures
Learn how to use Java's CompletableFuture.allOf to wait for multiple async tasks, collect results, and handle failures.

When you need to wait for several independent asynchronous tasks in Java, CompletableFuture.allOf is a standard way to combine them. This article explains how CompletableFuture.allOf works, what it returns, and how to use it correctly in real code.
What CompletableFuture.allOf Actually Does
CompletableFuture.allOf takes a varargs array of CompletableFuture<?> and returns a new CompletableFuture<Void>. It registers a completion callback on each input and completes when all input futures have completed normally. If any input completes exceptionally, the returned future completes exceptionally as well, with a CompletionException that has the failure as its cause. As a result, it may not wait for the remaining inputs to finish.
The key point is that the result type is Void. You do not get the individual results directly from the combined future. After the combined future completes normally, you can query each original future individually. This design keeps the API simple and avoids forcing a common type across heterogeneous futures.
Basic Usage: Waiting for Multiple Futures
The most straightforward use is to wait for several futures that run in parallel. For example, suppose you fetch data from three remote services concurrently:
CompletableFuture<String> userFuture = fetchUser();
CompletableFuture<String> orderFuture = fetchOrder();
CompletableFuture<String> invoiceFuture = fetchInvoice();
CompletableFuture<Void> all = CompletableFuture.allOf(userFuture, orderFuture, invoiceFuture);
all.join(); // waits for completion; throws CompletionException if any input failsIf all.join() returns normally, you can safely call userFuture.get(), orderFuture.get(), and invoiceFuture.get() without blocking, because they are guaranteed to be done. This pattern is useful when you need to wait for a batch of independent tasks before proceeding.
Collecting Results from allOf
Because allOf returns Void, you need a way to gather the results. A common pattern is to chain a thenApply on the combined future and collect the values inside that stage. Here is an example that combines the results into a list:
List<CompletableFuture<String>> futures = Arrays.asList(fetchUser(), fetchOrder(), fetchInvoice());
CompletableFuture<List<String>> combined = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList()));
List<String> results = combined.join();Notice that join() inside the thenApply is safe when the allOf stage completes normally, because all input futures are done. This avoids calling join() on individual futures before the whole batch has finished.
Handling Exceptions and Failures
allOf does not wait for every future to finish if one of them fails. If any input completes exceptionally, the combined future completes exceptionally with a CompletionException wrapping that failure. A call such as all.join() then throws instead of returning normally.
To recover from a failed input with a default value, apply exceptionally to each future before passing them to allOf:
CompletableFuture<String> userFuture = fetchUser().exceptionally(ex -> "default user");
CompletableFuture<String> orderFuture = fetchOrder().exceptionally(ex -> "default order");
CompletableFuture<String> invoiceFuture = fetchInvoice().exceptionally(ex -> "default invoice");
CompletableFuture<List<String>> all = CompletableFuture.allOf(userFuture, orderFuture, invoiceFuture)
.thenApply(v -> Arrays.asList(userFuture.join(), orderFuture.join(), invoiceFuture.join()));Because each input future has been turned into a normally completing future, allOf now waits for all three. If you instead need the batch to fail as soon as any input fails, keep the original futures and call allOf directly; the combined future will finish exceptionally as soon as the first failure is observed.
Combining allOf with thenApply and Other Stages
allOf is rarely the end of a pipeline. You typically chain further transformations on the combined future. Because the combined future is itself a CompletableFuture<Void>, you can use thenApply, thenAccept, or thenCompose to continue after all inputs are done.
For example, to run a final action after all downloads finish:
CompletableFuture<Void> all = CompletableFuture.allOf(download1, download2);
CompletableFuture<String> summary = all.thenApply(v -> {
// All downloads are complete; combine their contents
return download1.join() + download2.join();
});You can also use thenCompose to start another asynchronous task after the batch completes, avoiding blocking a thread.
Concurrency and Thread Pool Considerations
allOf itself does not create new threads. It relies on the thread pools used by the input futures. When you call join() on the combined future, the calling thread blocks until the combined future completes; normally that means all inputs have finished, but if any input fails, join() can throw before the whole batch finishes. If you call join() from a common pool thread, you risk thread starvation in high-concurrency scenarios.
A better approach is to use asynchronous chaining (thenApply, thenCompose) rather than blocking join() in the main flow. This allows the calling thread to return to the pool while the batch completes. For example:
List<CompletableFuture<String>> futures = Arrays.asList(download1, download2, download3);
CompletableFuture<List<String>> result = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.thenApply(v -> collectResults(futures));
result.thenAccept(results -> process(results));If you must block, be aware that join() throws CompletionException if any input future completes exceptionally. This is a runtime exception, unlike get() which throws checked exceptions. Choose the method that matches your error-handling style.
When Not to Use allOf
allOf is not the right tool when you need the result of the first completed future. In that case, anyOf is more appropriate. If you need to know which future failed or recover failures independently, attach whenComplete or exceptionally to each future rather than relying only on the combined future.
Also, if you have a large number of futures (thousands), allOf creates a completion counter and registers callbacks on each future. The overhead is small but not zero. For extremely large batches, consider processing them in smaller groups or using a custom aggregator.
Finally, remember that allOf does not guarantee that the input futures start concurrently. It only waits for them. If you want to start tasks in parallel, create the futures with an executor that supports parallelism, such as a fixed thread pool. The default common pool may not give you the concurrency you expect in constrained environments.
Practical Example: Parallel API Calls with Timeouts
A realistic use case is calling multiple external APIs in parallel and combining their responses. Here is a complete example with a timeout applied to each call. orTimeout is available in Java 9 and later:
ExecutorService executor = Executors.newFixedThreadPool(3);
CompletableFuture<String> user = CompletableFuture.supplyAsync(() -> api.getUser(), executor)
.orTimeout(2, TimeUnit.SECONDS);
CompletableFuture<String> orders = CompletableFuture.supplyAsync(() -> api.getOrders(), executor)
.orTimeout(2, TimeUnit.SECONDS);
CompletableFuture<String> invoice = CompletableFuture.supplyAsync(() -> api.getInvoice(), executor)
.orTimeout(2, TimeUnit.SECONDS);
CompletableFuture<List<String>> all = CompletableFuture.allOf(user, orders, invoice)
.thenApply(v -> Arrays.asList(user.join(), orders.join(), invoice.join()));
try {
List<String> results = all.get(5, TimeUnit.SECONDS);
// process results
} catch (TimeoutException e) {
// handle overall timeout
} catch (ExecutionException e) {
// handle one of the futures failing
} finally {
executor.shutdown();
}The orTimeout method ensures each individual future completes exceptionally if it takes too long. Because allOf completes exceptionally when any input does, the combined future will also finish at the first timeout. The get(5, TimeUnit.SECONDS) call adds an overall deadline independently of the per-future timeouts. This pattern is common in service orchestration where you want a fixed upper limit on the whole batch.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.