Creating Dedicated Thread Pools for CompletableFuture
You'll learn how to create custom thread pools specifically designed for your CompletableFuture workflows using Executors.newFixedThreadPool and newCachedThreadPool.
Why Create Dedicated Thread Pools?
While ForkJoinPool.commonPool() works well for general purposes, production applications often need isolated thread pools for different types of work. Think of it like having separate assembly lines in a factory: one for CPU-intensive tasks, another for I/O operations. This prevents one type of work from starving another.
Creating a Fixed Thread Pool
Executors.newFixedThreadPool(int nThreads) creates a pool with a fixed number of threads that persist for the pool's lifetime:
Executor fixedPool = Executors.newFixedThreadPool(10);
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> fetchFromDatabase(), fixedPool)
.thenApplyAsync(data -> transform(data), fixedPool);
This is ideal for predictable workloads where you know approximately how many concurrent operations you'll handle. For example, if you process 50 API requests concurrently, a pool of 50 threads ensures each request gets dedicated resources.
Creating a Cached Thread Pool
Executors.newCachedThreadPool() creates threads on-demand and reuses idle threads:
Executor cachedPool = Executors.newCachedThreadPool();
CompletableFuture<String> future = CompletableFuture
.supplyAsync(() -> processRequest(), cachedPool)
.thenComposeAsync(result -> callExternalAPI(result), cachedPool);
This is perfect for bursty, unpredictable workloads with many short-lived tasks. Threads are created as needed and terminated after 60 seconds of idleness, keeping resource usage efficient.
Choosing Between Them
- Fixed pool: Bounded resource usage, prevents thread explosion, better for steady loads
- Cached pool: Flexible scaling, better for sporadic workloads, risk of creating too many threads
Key Takeaway: Create dedicated thread pools using Executors.newFixedThreadPool() for predictable workloads or Executors.newCachedThreadPool() for variable workloads, then pass them to supplyAsync, thenApplyAsync, and other async methods to isolate CompletableFuture execution from the common pool.