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

Passing Custom Executors to Async Methods

How to provide a custom Executor to supplyAsync, runAsync, and other async methods using overloaded variants.

Passing Custom Executors to Async Methods

What you'll learn: How to control which thread pool executes your asynchronous operations by providing custom executors to CompletableFuture methods.

The Core Idea

Most CompletableFuture async methods come in two flavors: one that uses the default ForkJoinPool.commonPool(), and an overloaded variant that accepts an Executor parameter. By passing your own executor, you gain fine-grained control over threading behavior—crucial for performance tuning, resource isolation, or integration with existing thread pools.

How It Works

Methods like supplyAsync, runAsync, thenApplyAsync, thenAcceptAsync, thenRunAsync, thenComposeAsync, and thenCombineAsync all have overloaded versions accepting an Executor:

Executor customExecutor = Executors.newFixedThreadPool(4);

CompletableFuture<String> future = CompletableFuture
    .supplyAsync(() -> "Step 1", customExecutor)
    .thenApplyAsync(result -> result + " Step 2", customExecutor)
    .thenAcceptAsync(System.out::println, customExecutor);

Here, every async stage runs on your custom thread pool rather than the common pool. This is especially useful when you need dedicated threads for I/O operations, want to avoid starving the common pool, or need different thread configurations for different parts of your application.

When to Use Custom Executors

  • Resource isolation: Keep heavy tasks separate from lightweight ones
  • Thread configuration: Control thread counts, priorities, or naming
  • Integration: Reuse existing managed executors from frameworks
  • Testing: Inject controllable executors for deterministic tests

Key Takeaway: Always use the overloaded async method variants with custom executors when you need control over threading behavior—simply pass your Executor as the final parameter to any async method.