Thread pools
A thread pool is a fixed set of worker threads that stay alive and take tasks from a shared queue. Reusing threads avoids the cost of creating one per unit of work, and capping their number stops the machine being flooded.
Detailed Explanation
A pool answers one question: how much work may run at once? Everything else about it, the queue, the sizing, the rejection policy, follows from that.
The mechanics are plain. Worker threads loop forever, pulling the next task off a BlockingQueue and running it. When the queue is empty they block, costing nothing but memory. When tasks arrive faster than they can be run, the queue grows. This is why the queue, not the thread count, usually decides how your service behaves under load.
ThreadPoolExecutor is the real implementation behind almost every pool you use, and its constructor spells out the whole design: core pool size, maximum pool size, keep-alive time for threads above the core size, the queue, a thread factory, and a rejection handler. The Executors factory methods are shortcuts over it, and the shortcuts hide the sharp edges.
| Factory method | Threads | Queue | The trap |
|---|---|---|---|
newFixedThreadPool(n) | exactly n | unbounded | never rejects, so overload becomes heap growth |
newCachedThreadPool() | unbounded | direct handoff | one thread per queued task, thousands of threads under a spike |
newSingleThreadExecutor() | 1 | unbounded | serialises everything, easy to deadlock by waiting on your own task |
newVirtualThreadPerTaskExecutor() | not pooled | none | Java 21, unsuited to CPU-bound work |
Sizing depends on what the tasks do. CPU-bound work wants roughly availableProcessors() threads; more than that adds context switches without adding throughput. Blocking work wants more, because most threads are waiting rather than computing. The classic estimate is cores × (1 + waitTime / computeTime), so a task that waits 90 ms on the network and computes for 10 ms justifies about ten threads per core. Measure rather than trust the formula.
The cost is concrete. Each platform thread reserves around 1 MB of stack address space, so a 500-thread pool is a memory decision, not only a scheduling one. Queued tasks hold their arguments alive, so a deep queue can pin a lot of heap. And a request sitting in a queue for eight seconds is worse than a request rejected in one millisecond, because the caller has usually given up already.
That is what a bounded queue plus a rejection policy buys you: honest back pressure. AbortPolicy throws RejectedExecutionException, the default. CallerRunsPolicy makes the submitting thread run the task, which slows down the producer, a crude but effective brake. DiscardPolicy and DiscardOldestPolicy drop work silently and are rarely what you want.
Name your threads. A stack trace on pool-3-thread-7 tells you nothing; one on pricing-io-7 tells you which subsystem stalled.
On Java 21, blocking I/O no longer needs a pool at all. Virtual threads are cheap enough to create one per task, so pools are increasingly reserved for CPU-bound work and for deliberately limiting concurrency against a fragile downstream system.
Code Examples
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class BoundedPool {
public static void main(String[] args) {
// Named threads make thread dumps and logs readable (Java 21 builder API).
ThreadFactory factory = Thread.ofPlatform().name("pricing-io-", 0).factory();
try (ThreadPoolExecutor pool = new ThreadPoolExecutor(
4, // core threads, kept alive when idle
8, // ceiling once the queue is full
60, TimeUnit.SECONDS, // idle timeout for the extra 4
new ArrayBlockingQueue<>(100), // bounded: back pressure, not OOM
factory,
new ThreadPoolExecutor.CallerRunsPolicy())) { // full? the submitter runs it itself
for (int i = 0; i < 500; i++) {
int id = i; // captured value must be effectively final
pool.execute(() -> System.out.println("task " + id
+ " on " + Thread.currentThread().getName()));
}
} // ThreadPoolExecutor is an ExecutorService, so close() shuts it down and waits
}
}import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Sizing {
public static void main(String[] args) {
int cores = Runtime.getRuntime().availableProcessors();
// CPU-bound: one thread per core. Extra threads only add context switches.
try (ExecutorService cpu = Executors.newFixedThreadPool(cores)) {
cpu.execute(() -> { long sum = 0; for (int i = 0; i < 1_000_000; i++) sum += i; });
}
// I/O-bound on Java 21: skip sizing entirely, one virtual thread per task.
try (ExecutorService io = Executors.newVirtualThreadPerTaskExecutor()) {
io.execute(() -> System.out.println("waiting on the network is cheap here"));
}
}
}Common Gotchas
An unbounded queue turns overload into a memory leak
`newFixedThreadPool` accepts every task forever. The symptom is not a rejection but a slowly filling heap and response times that climb until the process dies. Always pick the queue bound deliberately for untrusted load.
Waiting inside a single-thread pool deadlocks it
if a task running on a one-thread pool submits another task to the same pool and calls `get()`, the worker is blocked waiting for work only it could run. The pool never recovers.
`newCachedThreadPool` has no ceiling
it creates a new thread whenever no idle one is free. A traffic spike can produce thousands of platform threads, roughly 1 MB of stack each, and the machine starts swapping or the JVM fails to create more threads.
Core threads do not shrink by default
threads up to the core size stay alive even when idle. Call `allowCoreThreadTimeOut(true)` if a mostly idle pool holding threads matters to you.