Library contents

Java CompletableFuture.allOf

Complete both independent calculations before combining the values in the report.

A simple example

CompletableFuture.allOf

  1. Start with Two tasks returning 2 and 3
  2. Do this Wait for both, then add
  3. Result 5
Only after both tasks finish are their two results combined.

Syntax

Java 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.java

Wait 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.

Result25
Main.java
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());
    }
}
Output
25

The order in which the tasks finish is unimportant. The report waits for both totals.

Advertisements

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?

GivenNorth 12 · South 8
Worked result20

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?

GivenDesk A 3 · Desk B 15
Worked result18

What to watch for

If a task fails, join can throw CompletionException. Decide where to handle an incomplete report.

Documentation for CompletableFuture.allOf