Performance Benefits of Parallel Combination
What you'll learn: How to measure the actual speedup gained when using thenCombine to execute two independent tasks in parallel versus running them sequentially.
Why Parallel Combination Matters
When you have two independent tasks that don't depend on each other, running them sequentially wastes time. If Task A takes 2 seconds and Task B takes 3 seconds, sequential execution takes 5 seconds total. With thenCombine, both tasks start simultaneously, so the total time becomes approximately 3 seconds—the duration of the longest task.
Think of it like cooking: If you need to boil pasta (10 minutes) and chop vegetables (5 minutes), doing them sequentially takes 15 minutes. But if you start the water boiling while you chop, you're done in 10 minutes.
Measuring the Speedup
// Sequential approach
long start = System.currentTimeMillis();
CompletableFuture<String> result1 = CompletableFuture.supplyAsync(() -> {
sleep(2000); // simulate 2-second task
return "Task1";
}).thenCompose(r -> CompletableFuture.supplyAsync(() -> {
sleep(3000); // simulate 3-second task
return r + " Task2";
}));
result1.join();
long sequential = System.currentTimeMillis() - start; // ~5000ms
// Parallel approach with thenCombine
start = System.currentTimeMillis();
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
sleep(2000);
return "Task1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
sleep(3000);
return "Task2";
});
future1.thenCombine(future2, (a, b) -> a + " " + b).join();
long parallel = System.currentTimeMillis() - start; // ~3000ms
System.out.println("Speedup: " + (sequential / (double) parallel) + "x");
The speedup is roughly 1.67x in this example—you've saved 2 seconds.
Key Takeaway: thenCombine provides measurable performance benefits by executing independent tasks in parallel, reducing total execution time to approximately the duration of the longest task rather than the sum of all tasks.