CKTIS / Java
`CompletableFuture.thenCombine`: Combine Two Results
`thenCombine` creates a new `CompletableFuture` whose value is computed only after both input stages complete normally, for example to add the counts from two independent operations.
Version: Java SE 21
Syntax
public <U, V> CompletableFuture<V> thenCombine(CompletionStage<? extends U> other, BiFunction<? super T, ? super U, ? extends V> fn)CompletableFuture.thenCombine registers a function fn that depends on two stages. Calling left.thenCombine(right, fn) neither starts the input computations nor blocks waiting for their results. fn can run only after both stages complete normally. It receives the result of left first and that of right second, regardless of completion order.
T is the result type of left, and U is the result type of the other stage; they can differ. right can be any compatible CompletionStage, not necessarily a CompletableFuture. The value returned by the BiFunction becomes the result of type V in the new CompletableFuture<V>. Use thenCompose when the first result is needed to choose or start the next stage.
The non-Async form does not guarantee a separate thread. If both results are already available, the function may run before thenCombine returns. thenCombineAsync(other, fn) uses the default asynchronous execution facility, while thenCombineAsync(other, fn, executor) uses the supplied Executor.
If either input completes exceptionally, including by cancellation, fn is skipped. In OpenJDK 21, thenCombine waits for both inputs to complete before completing the dependent stage exceptionally. If the other input never completes, the dependent stage can remain incomplete indefinitely. If both inputs fail, the reported cause can come from either one. An exception thrown by fn also makes the dependent stage complete exceptionally; reading such a result with join() throws CompletionException.
Examples
import java.util.concurrent.CompletableFuture;
public class CombineCounters {
public static void main(String[] args) {
var leftCount = new CompletableFuture<Integer>();
var rightCount = new CompletableFuture<Integer>();
CompletableFuture<Integer> total =
leftCount.thenCombine(rightCount, Integer::sum);
rightCount.complete(24);
System.out.println(total.isDone());
leftCount.complete(18);
System.out.println(total.join());
}
}Result
false 42
`rightCount` completes first, but `total.isDone()` still returns `false`. Only after `leftCount` completes does `Integer::sum` receive `18` and `24`, and `total.join()` returns `42`.
Related lessons
- Java · Lesson 51 · Intermediate · Version: 2