Combining Futures: allOf and anyOf
Wait for all futures with allOf and race them with anyOf to implement timeout and fallback logic.
Why Combine Futures?
When independent async tasks can run in parallel, you want to wait for all (or the first) to complete before proceeding. allOf and anyOf handle both cases.
allOf: Wait for All Futures
CompletableFuture.allOf(futures...) returns a CompletableFuture<Void> that completes when ALL input futures complete. If any fails, allOf also fails.
CompletableFuture<String> f1 = fetchUserAsync();
CompletableFuture<List<Order>> f2 = fetchOrdersAsync();
CompletableFuture<Double> f3 = fetchBalanceAsync();
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2, f3);
all.join(); // wait for all three
String user = f1.join();
List<Order> orders = f2.join();
Double balance = f3.join();All lessons in this course
- Creating and Completing CompletableFutures
- Chaining with thenApply and thenCompose
- Combining Futures: allOf and anyOf
- Error Handling and Async HTTP Pipeline