Sub topic 9
Choosing an executor
An executor decides which thread runs each stage of a CompletableFuture chain. This chapter explains the default, when to replace it, and how to size and manage the replacement.
It assumes you know supplyAsync, thenApply, and join from earlier chapters. It also assumes you know what an ExecutorService and a thread pool are.
What runs your code by default
supplyAsync(supplier) and runAsync(runnable) have overloads with and without an Executor argument. Without one, the task goes to the default executor, which is the JVM-wide common pool, ForkJoinPool.commonPool().
The common pool has these properties:
- It is shared by the whole JVM. Parallel streams, other libraries, and every
CompletableFuturethat omits an executor compete for the same threads. - Its default parallelism is the number of available processors minus one. You can change it with
-Djava.util.concurrent.ForkJoinPool.common.parallelism=N. - Its threads are daemon threads. The JVM can exit while common-pool tasks are still running.
- If the common pool's parallelism is 1 or less, which happens on a one- or two-core machine,
CompletableFuturedoes not use it. It starts a new thread for every task instead. Code that behaves one way on your laptop can behave differently in a small container.
You can ask for the default executor in Java 9 and later with CompletableFuture.defaultExecutor(), but that method belongs to an instance of the class. Treat the common pool as "the executor you get when you pass none".
Seeing the difference
This program prints the thread that ran each task. The custom pool uses a named, daemon thread factory so the output is readable and the JVM can exit even if you forget to shut the pool down.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ExecutorChoice {
static ExecutorService namedPool(String prefix, int size) {
AtomicInteger counter = new AtomicInteger(1);
return Executors.newFixedThreadPool(size, r -> {
Thread t = new Thread(r, prefix + "-" + counter.getAndIncrement());
t.setDaemon(true);
return t;
});
}
public static void main(String[] args) {
ExecutorService io = namedPool("io", 8);
try {
CompletableFuture<String> common = CompletableFuture
.supplyAsync(() -> Thread.currentThread().getName());
CompletableFuture<String> custom = CompletableFuture
.supplyAsync(() -> Thread.currentThread().getName(), io);
System.out.println("default: " + common.join());
System.out.println("custom: " + custom.join());
} finally {
io.shutdown();
}
}
}On a machine with several cores, the output looks like this:
default: ForkJoinPool.commonPool-worker-1
custom: io-1Why the common pool is a poor home for blocking work
The common pool is sized for CPU-bound work. If you have 8 cores, it has 7 threads. A task that blocks, for example on a JDBC call, an HTTP request, or Thread.sleep, keeps its thread and does no useful work while it waits.
Seven concurrent blocking tasks on that pool leave no thread for anything else. The eighth task waits in the queue, and so does every parallel stream and every other CompletableFuture in the JVM. Nothing fails with an error. The application becomes slow and the cause is hard to see.
The ForkJoinPool can compensate for some blocking, but only for blocking that goes through ForkJoinPool.managedBlock. A plain Thread.sleep or a socket read gets no such help.
Matching the executor to the work
| Kind of work | Suggested executor | Sizing hint |
|---|---|---|
| Short, CPU-bound computation | The common pool, or a fixed pool | About the number of cores |
| Blocking I/O (database, HTTP, files) | A dedicated fixed pool, or a virtual-thread executor on Java 21+ | Larger than the core count, sized from measured wait time |
| Work that must be isolated from the rest of the app | Its own pool per dependency | Set per dependency so one slow service cannot take every thread |
| Tests that need predictable ordering | A single-thread executor | One thread |
A common starting formula for I/O pools is threads = cores * (1 + wait time / compute time). If a task spends 90 ms waiting and 10 ms computing, each core can keep about 10 tasks in flight. Treat the result as a first guess and adjust it from measurements. A pool that is too large wastes memory and can overload the service it calls. A pool that is too small makes tasks queue.
Keeping pools separate in a real service
A realistic design gives each kind of work its own executor and passes it explicitly. The class below owns two pools and uses the right one for each stage.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class PriceService implements AutoCloseable {
private final ExecutorService ioPool = pool("io", 16);
private final ExecutorService cpuPool =
pool("cpu", Runtime.getRuntime().availableProcessors());
private static ExecutorService pool(String prefix, int size) {
AtomicInteger n = new AtomicInteger(1);
return Executors.newFixedThreadPool(size, r -> {
Thread t = new Thread(r, prefix + "-" + n.getAndIncrement());
t.setDaemon(true);
return t;
});
}
private String fetchRate(String currency) {
sleep(100); // stands in for a slow network call
return "1.25";
}
private static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public CompletableFuture<Double> priceInEuro(double dollars) {
return CompletableFuture
.supplyAsync(() -> fetchRate("EUR"), ioPool)
.thenApplyAsync(rate -> dollars * Double.parseDouble(rate), cpuPool);
}
@Override
public void close() {
ioPool.shutdown();
cpuPool.shutdown();
}
public static void main(String[] args) {
try (PriceService service = new PriceService()) {
System.out.println(service.priceInEuro(10).join());
}
}
}This prints 12.5. The blocking call runs on ioPool. The multiplication runs on cpuPool because the Async variant receives an explicit executor. Chapter "Understanding the Async method variants" covers when to use that variant. For now, note that the executor is chosen per stage.
The executor does not carry over between stages
An executor passed to supplyAsync applies to that stage only. Later stages do not inherit it. The rules are:
- A non-async stage such as
thenApply(f)runs on the thread that completes the previous stage. If the previous stage has already completed when you attach the new one, it runs immediately on the calling thread. - An
Asyncstage without an executor, such asthenApplyAsync(f), runs on the default executor, which is the common pool. It does not use the executor of the earlier stage. - An
Asyncstage with an executor, such asthenApplyAsync(f, pool), runs on that executor.
So this chain moves back to the common pool at its second stage:
CompletableFuture
.supplyAsync(() -> "a", myPool)
.thenApplyAsync(s -> s + "b"); // runs on the common pool, not myPoolIf you want every stage on your pool, pass it to every Async call. This is the most common way for a blocking stage to end up on the common pool by accident.
Managing the lifecycle of a pool
Threads from Executors.newFixedThreadPool are non-daemon by default. A program whose main method has finished will not exit while such a pool is alive and idle, so you must shut it down. Use one of these approaches:
- Call
shutdown()in afinallyblock, as the examples do. Tasks already submitted still run, and new submissions are rejected. - Use a thread factory that creates daemon threads, but only for work that is safe to lose when the JVM exits.
- Create the pool once for the life of the application and close it on application shutdown. Do not create a pool per request. A new pool per call defeats the purpose and leaks threads.
Rejection behaves in a way you may not expect. When an executor refuses a task, for example because it was shut down or a bounded queue is full, supplyAsync throws RejectedExecutionException from the calling method. It does not return a failed future. Executors.newFixedThreadPool uses an unbounded queue, so it never rejects for lack of space, but under overload the queue can grow until memory runs out. If you need back-pressure, build a ThreadPoolExecutor with a bounded ArrayBlockingQueue and a rejection policy you chose on purpose.
Common mistakes
- Using the default executor for blocking calls, as described above.
- Creating a new
ExecutorServiceinside a method that runs often, and never shutting it down. - Assuming a custom executor applies to the whole chain.
- Sizing a pool by guesswork and never measuring queue length or task wait time.
- Running tasks that wait on other tasks in the same fixed pool. If every thread is blocked in
join()on a task that is still queued, the pool deadlocks. Give dependent blocking layers separate pools.
Exercise
A service runs CompletableFuture.supplyAsync(() -> httpClient.get(url), pool).thenApplyAsync(response -> parse(response)) and uses a 16-thread I/O pool named pool. Under load, unrelated parallel streams in the same JVM slow down. Explain the likely cause and give one fix.
Show answer
thenApplyAsync was called without an executor, so the parse stage runs on the common pool, which is shared with parallel streams. If parse is slow or blocks, it occupies common-pool threads. The fix is to pass an executor to that stage, for example thenApplyAsync(response -> parse(response), cpuPool). If parsing is trivially short, a non-async thenApply is also acceptable, because it runs on the thread that completed the HTTP stage.
Exercise
On a machine with 4 cores, how many threads does the common pool have by default, and what happens to the default executor on a machine where the common pool's parallelism is 1 or less?
Show answer
The default parallelism is the processor count minus one, so 3 threads. When the common pool's parallelism is 1 or less, CompletableFuture starts a new thread for each task instead of using the common pool.