Course contentsShow
← Java
Lesson 2827 of 2,87051. CompletableFutureFree lesson

Parallel Execution: Both Futures Run Simultaneously

Understand that thenCombine executes both CompletableFutures in parallel, not sequentially.

Parallel Execution: Both Futures Run Simultaneously

You'll learn how thenCombine executes both CompletableFutures in parallel rather than waiting for one before starting the other.

The Key Advantage of thenCombine

When you use thenCombine, both CompletableFutures start executing at the same time, not sequentially. This is fundamentally different from thenCompose, which waits for the first future to complete before starting the second one.

Think of it like ordering food at two different restaurants simultaneously versus ordering from one restaurant, waiting for delivery, then ordering from the second. With thenCombine, both restaurants are cooking your food at the same time.

How Parallel Execution Works

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
    // This starts immediately
    return 10;
});

CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
    // This ALSO starts immediately, not waiting for future1
    return "Result";
});

CompletableFuture<String> combined = future1.thenCombine(future2, (num, str) -> {
    return num + " " + str;
});

Both future1 and future2 begin executing as soon as supplyAsync is called. The thenCombine operation waits for both to finish, then applies the combining function.

Time Savings from Parallelism

If future1 takes 5 seconds and future2 takes 3 seconds, the total execution time is approximately 5 seconds (the longest task), not 8 seconds (sum of both). This parallel execution is automatic—you don't need to coordinate threads manually.

Key Takeaway: thenCombine automatically runs both CompletableFutures in parallel, combining their results only after both complete, making it ideal for independent operations that can run simultaneously.