CompletableFuture thenCombine Two Results

Merge two independent futures with thenCombine: the callback fires only once both stages complete, then ordinary thenApply chains continue downstream.

JavaData Fetching

Code

snippet
import java.util.concurrent.CompletableFuture;

public class CombineTwoQuotes {

    public static void main(String[] args) throws Exception {
        CompletableFuture<Integer> base = CompletableFuture.supplyAsync(() -> 199);
        CompletableFuture<Integer> tax = CompletableFuture.completedFuture(17);

        // 两侧 results 都就绪才触发 thenCombine 回调
        CompletableFuture<Integer> total = base.thenCombine(tax, Integer::sum);

        // 合并结果直接进入下游 thenApply 续链
        CompletableFuture<String> receipt = base
                .thenCombine(tax, (b, t) -> b + " + " + t)
                .thenApply(part -> "receipt: " + part + " = " + total.join());

        System.out.println("total = " + total.get());
        System.out.println(receipt.get());
    }
}

The join point of two independent futures

base = CompletableFuture.supplyAsync(() -> 199) runs on a pool thread while tax = CompletableFuture.completedFuture(17) is already done. base.thenCombine(tax, Integer::sum) registers a merge whose callback fires only once both sides are complete — with a completed future on one side, the trigger is effectively “when base finishes”. The second chain combines the same two futures into the string 199 + 17 and then continues with .thenApply(part -> "receipt: " + part + " = " + total.join()).

What the run prints

total = 216
receipt: 199 + 17 = 216

total.get() returns the summed 216. The receipt line shows both compositions at work: the string-combining thenCombine produced 199 + 17, and the downstream thenApply appended the numeric total by calling total.join() — already computed by then, so it never blocks.

The line that waits for both sides

CompletableFuture<Integer> total = base.thenCombine(tax, Integer::sum);

If either input later completes exceptionally, the combined future completes exceptionally too — the merge point is the single place both result paths converge.

FAQ

What does CompletableFuture thenCombine Two Results print when run?
Run it as a complete program — the output lines carry labels such as `total =`.