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
- Start with Completed values 1 and 2
- Do this Combine the two values with addition
- Result 3
Apply it to a real problem
- Start with East subtotal 5 and west subtotal 7
- Do this Complete the east stage, then the west stage
- Result Pending first, then 12
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
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());
}
}
false 12