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

thenCombineAsync: Controlling Execution Thread Pool

Learn how thenCombineAsync allows specifying a custom executor for the combining function.

thenCombineAsync: Controlling Execution Thread Pool

What You'll Learn

You'll learn how to control which thread pool executes the combining function when merging two independent CompletableFuture results using thenCombineAsync.

The Core Concept

You already know that thenCombine merges two independent futures using a BiFunction. By default, the combining function runs on whichever thread completes second (or the common pool). But what if you want explicit control over where that combining logic executes?

thenCombineAsync with a custom executor gives you that control. You pass an Executor as the third argument, ensuring the combining function runs in your chosen thread pool.

Why This Matters

Consider combining results from a database query and an API call, then performing complex validation logic. You might want that validation to run on a specialized thread pool designed for CPU-intensive work, rather than the default pool or the I/O thread that happened to finish last.

The Syntax

CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 10);
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 20);

ExecutorService customExecutor = Executors.newFixedThreadPool(2);

CompletableFuture<Integer> result = future1.thenCombineAsync(
    future2, 
    (a, b) -> a + b,
    customExecutor  // Your custom executor here
);

The combining function (a, b) -> a + b now always executes on customExecutor, regardless of which future completes first or what threads they used.

Think of It Like This

It's like having two delivery trucks arrive at different times, but you've specifically hired a third-party inspector (your custom executor) to check both packages—rather than having whoever arrived second do the inspection.

Key Takeaway: Use thenCombineAsync with a custom Executor when you need precise control over which thread pool handles the combining logic after both independent futures complete.