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

Using thenApplyAsync with Custom Executor

Controlling the thread pool for async transformations by passing a custom Executor to thenApplyAsync.

Using thenApplyAsync with Custom Executor

What you'll learn: How to control which thread pool executes your asynchronous transformations by providing a custom Executor to thenApplyAsync.

Why Custom Executors Matter

You've seen that thenApplyAsync runs transformations asynchronously, defaulting to ForkJoinPool.commonPool(). But what if you need different thread pool characteristics—perhaps dedicated threads for I/O-heavy transformations, or isolation from the common pool to prevent resource contention? That's where custom executors shine.

Providing Your Own Executor

thenApplyAsync has an overloaded variant that accepts an Executor as its second parameter:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello");

ExecutorService customPool = Executors.newFixedThreadPool(4);

CompletableFuture<Integer> result = future.thenApplyAsync(
    s -> s.length(),
    customPool  // Your transformation runs here
);

In this example, instead of using the common pool, the transformation (s -> s.length()) executes on one of the four threads in customPool.

When to Use This Pattern

Workload isolation: Separate CPU-intensive transformations from I/O operations by using distinct pools.

Resource control: Limit concurrency for database queries or API calls by using a bounded thread pool.

Testing: Inject a controlled executor for predictable behavior in tests.

Performance tuning: Match pool size to your specific workload characteristics.

Thread Safety Reminder

Remember to shut down custom executors when you're done—they won't clean up automatically like the common pool does.

Key Takeaway: thenApplyAsync(function, executor) lets you explicitly control which thread pool runs your transformation, giving you fine-grained control over resource allocation and execution behavior in your asynchronous pipelines.