Java CompletableFuture.allOf
Complete both independent calculations before combining the values in the report.
A simple example
CompletableFuture.allOf
- Start with Two tasks returning 2 and 3
- Do this Wait for both, then add
- Result 5
Syntax
CompletableFuture.allOf(east, west).join()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaWait for two shop totals before producing a report
Two shops produce their totals independently and may finish at different times. Wait for both results before creating the shared report so its final figure includes both contributions.
import java.util.concurrent.CompletableFuture;
class Main {
public static void main(String[] args) throws Exception {
var east = CompletableFuture.supplyAsync(() -> 10 + 4);
var west = CompletableFuture.supplyAsync(() -> 3 + 8);
CompletableFuture.allOf(east, west).join();
System.out.println(east.join() + west.join());
}
}
25
The order in which the tasks finish is unimportant. The report waits for both totals.
Combine two gallery entrances
Separate workers count admissions from the north and south doors. Wait until both workers have completed before summing their counts. What total can the coordinator publish?
Combine shift checkouts
Two desks count processed books independently before closing. Wait until both workers have completed before summing their counts. What total can the coordinator publish?
What to watch for
If a task fails, join can throw CompletionException. Decide where to handle an incomplete report.