ExecutorService, thread pools and virtual threads in Java
Why services die from a growing queue or hang on shutdown; choosing queues, rejection policies and pool sizes; virtual threads since Java 21, pinning before and after JDK 24, ThreadLocal leaks; reviewing AI-written executor code.
On this page
1. The problem
During a sale, the service sends email through Executors.newFixedThreadPool(10). SMTP slows from 50 ms to 2 s, the queue grows to 200,000 tasks, the heap climbs steadily and the pod dies with OutOfMemoryError. Not one "rejected" log line; every queued email dies with the pod.
2. Key idea
A pool is a few workers plus a waiting line; an unbounded line turns overload into latency and memory. A pool grows past core only when the queue is full; if the queue never fills, max and the rejection policy are useless.
Every executor must answer three questions: how many jobs run at once, how many may wait, and what happens when it's full.
| Choice | Use when | Don't use when |
|---|---|---|
Hand-declared ThreadPoolExecutor, bounded queue |
CPU-bound work; one pool per kind of work (bulkhead) | tens of thousands of concurrent I/O waits |
Virtual thread per task + Semaphore |
DB, HTTP, fan-out, sequential blocking code | pure CPU work; JDK 21–23 with lots of synchronized around I/O |
AbortPolicy |
report overload clearly: return 503 or 429 | losing a task is unacceptable |
CallerRunsPolicy |
back-pressure: the submitter slows down | the submitter is an event loop (Netty, Kafka consumer) |
2.1 How many threads?
- CPU bound: ≈ number of cores.
- I/O bound: ≈ cores × (1 + wait / compute). 8 cores, 40 ms DB wait, 10 ms compute: 40 threads.
- Cap by the narrowest resource: 200 threads and 20 DB connections means 180 threads waiting.
2.2 How are virtual threads different?
Virtual threads are cheap enough to create millions. When one blocks on I/O, the JVM unmounts it from its carrier thread (an OS thread; one per core by default). It is pinned when it can't be unmounted: on JDK 21–23, blocking inside synchronized; since JDK 24 (JEP 491), mostly native calls.
Pool threads don't die: a ThreadLocal without remove() leaks into the next task.
3. In Java
An explicit pool, virtual threads limited by a Semaphore, ThreadLocal cleaned in the right place.
var cpuPool = new ThreadPoolExecutor(8, 8, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(500), // bounded queue
new ThreadPoolExecutor.AbortPolicy()); // full: RejectedExecutionException
var dbPermits = new Semaphore(30); // = HikariCP connections
try (var io = Executors.newVirtualThreadPerTaskExecutor()) { // close() waits for all tasks
io.submit(() -> {
dbPermits.acquire();
try { return repo.load(id); } finally { dbPermits.release(); }
});
}
try { CURRENT_USER.set(user); handle(request); }
finally { CURRENT_USER.remove(); } // remove where you setOther languages: Go uses buffered channels or semaphore.Weighted; Node.js limits with p-limit.
Exceptions in tasks, and shutting a pool down properly
submit(...)stores the exception in theFuture: no log, no handler. If nobody callsget(), the error vanishes. Withexecute(...)the exception kills the worker and reaches theUncaughtExceptionHandler.@Asyncmethods returningvoidsend errors toAsyncUncaughtExceptionHandler, which only logs by default.- Pool threads are non-daemon: forget to shut down and the JVM won't exit. Use
shutdown()→ a boundedawaitTermination(say 30 s) →shutdownNow(). Spring beans (ThreadPoolTaskExecutor) shut down when the context closes. - MDC and
SecurityContextlive inThreadLocaland don't cross to another executor by themselves: use aTaskDecoratorto carry them.
4. Working with AI
Hand to AI: load tests, a pool config from numbers you provide, summarising thread dumps or JFR recordings.
Check in AI-written code:
- No
newFixedThreadPoolornewCachedThreadPoolin production; queues are bounded. - Every
submit()has someone reading theFuture, or atry/catch+ log inside the task. - Virtual threads aren't pooled; a
Semaphoreguards the resource behind them. - Every
ThreadLocal.sethas aremove()infinally; the JDK version is stated.
5. Exercises
Exercise 1: Review a price fetcher
fetchPrice(id) takes 100–300 ms and sometimes fails or hangs. The supplier allows 10 concurrent requests; 100 ids must finish within 4 seconds. The AI says "safe because the machine only has 10 cores". Find the bugs and fix it.
Map<Integer, Long> fetchAll(List<Integer> ids) throws Exception {
Map<Integer, Long> prices = new HashMap<>();
try (var ex = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = ids.stream().map(id -> ex.submit(() -> fetchPrice(id))).toList();
for (int i = 0; i < ids.size(); i++) prices.put(ids.get(i), futures.get(i).get());
}
return prices;
}Solution to Exercise 1
- Cores don't limit virtual threads: all 100 requests fire at once and the supplier returns 429.
- No deadline: one hanging request hangs the whole batch.
- One
get()that throws loses every result.
Test: a fake fetchPrice that records the peak number of concurrent calls (it reports 100), plus one id that hangs forever (the method never returns).
Fix: a Semaphore(10) around fetchPrice; invokeAll(tasks, 4, SECONDS) to cancel overdue tasks; walk each Future and collect errors into a failures map instead of throwing.
Exercise 2: Read an incident
JDK 21, a 10-core machine, spring.threads.virtual.enabled=true just turned on. Throughput drops from 1,200 to 90 requests/s with CPU at 5%. JFR shows thousands of jdk.VirtualThreadPinned events, with stacks stopping inside synchronized in an old JDBC driver. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: pinning. The driver blocks on I/O inside
synchronized, each virtual thread holds one of the 10 carriers, so only about 10 requests run at once. - 15 minutes: turn the flag off so Tomcat goes back to its platform thread pool; keep the JFR recording.
- Root fix: move to JDK 25 (JEP 491) or upgrade the driver; rerun the load test and check that
jdk.VirtualThreadPinnedonly shows native cases.
Summary
- A pool grows past
coreonly when the queue is full; an unbounded queue turns overload into OOM. - The thread count is capped by the narrowest resource behind it, not just cores.
- Virtual threads are for I/O waits; don't pool them, limit them with a
Semaphore. ThreadLocalin a pool:remove()infinally.
Read more: Part 4: CompletableFuture.
Practice interview questions on this topic
- Why use a thread pool instead of new Thread()? How do Executor, ExecutorService and ThreadPoolExecutor differ?
- How do you choose the size and configuration of a production thread pool?
- How does ThreadLocal leak in a thread pool? Why do async logs lose the trace id?
- What do Java 21 virtual threads help with, what don't they, and do you still need CompletableFuture?
- How do Future and CompletableFuture differ? When do you use thenApply, thenCompose and thenApplyAsync?
Comments
Community rules