Combine two independent subtotals in Java

thenCombine applies a function when two completion stages have both completed normally. It returns a new stage for the combined result. An input failure also makes the combined stage complete exceptionally. The example explicitly completes both inputs, making the sequence reproducible without sleeps.

A simple example

Combine the two values with addition

  1. Start with Completed values 1 and 2
  2. Do this Combine the two values with addition
  3. Result 3
Combining waits for both inputs before applying the function.

Apply it to a real problem

  1. Start with East subtotal 5 and west subtotal 7
  2. Do this Complete the east stage, then the west stage
  3. Result Pending first, then 12
The total becomes available only after both regions have supplied a count.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.concurrent.CompletableFuture;

class Main {
    public static void main(String[] args) throws Exception {
        var east = new CompletableFuture<Integer>();
        var west = new CompletableFuture<Integer>();
        var total = east.thenCombine(west, Integer::sum);
        east.complete(5);
        System.out.println(total.isDone());
        west.complete(7);
        System.out.println(total.join());
    }
}
Output
false
12

Official Java documentation