Lesson · Executors, Thread Pools & Async Programming
Thread Pools: the rule behind every pool factory
16 min readThread Pools
Every factory in Executors is one ThreadPoolExecutor construction with chosen parameters. Learn the constructor and its growth rule, core threads first, then the queue, then growth to max, then the rejection handler, and you can read any pool in a codebase, including the one whose maximumPoolSize has never mattered because its queue is unbounded.
A pool is a policy object, and the factories are presets
Executors.newFixedThreadPool(8) looks like a different creature from Executors.newCachedThreadPool(), but both are presets over a single class: ThreadPoolExecutor. Every pool question, how many threads, what waits, what happens when nothing can wait, who gets reused, who stops them, is an argument to its constructor, and the factories simply fix those arguments for you.
The parameters read as a sentence: corePoolSize threads run work before anything is allowed to queue; maximumPoolSize is the ceiling that becomes reachable only once the queue is full; keepAliveTime retires idle threads above core; the workQueue holds waiting tasks; the threadFactory creates and names the workers; the rejection handler decides what happens when the queue refuses the task and no worker can be added.
Reading the constructor once is enough to decode every pool you will meet. The hard part is not the parameter list, it is the order in which the pool consults it, and that order is the next section.
ThreadPoolExecutor pool = new ThreadPoolExecutor( 2, 4, 60, TimeUnit.SECONDS, // core, max, and the idle timeout above core new ArrayBlockingQueue<>(3), // bounded queue: a full queue is now a state namedFactory, // threads you can recognise in a dump new ThreadPoolExecutor.CallerRunsPolicy()); // the full case has an owner
The factories are presets; ThreadPoolExecutor is the machine. If you cannot name the preset's queue, you cannot predict the pool.
The growth rule, in order
Every submitted task walks the same four-branch rule, and the branches are checked in order rather than chosen by preference. Core first, then the queue, and only then growth beyond core. The middle step is the one that surprises people: the pool prefers waiting over adding a thread, so extra threads appear only when waiting becomes impossible.
| Work queue | What happens under sustained load | Is maximumPoolSize ever reached? |
|---|---|---|
| Unbounded (a LinkedBlockingQueue with no capacity) | tasks accumulate forever; memory is the only ceiling | never: core is the effective maximum |
| Bounded (an ArrayBlockingQueue of capacity n) | n tasks wait, and beyond that the pool grows to max | yes: growth is the designed response to a full queue |
| SynchronousQueue (no capacity at all) | every task must hand off to a waiting thread immediately | max becomes the effective concurrency limit |
| Priority queue (PriorityBlockingQueue) | tasks wait ordered by priority instead of FIFO | same as a bounded queue, and starvation becomes possible |
- Fewer than corePoolSize workers are running: create a new worker and run the task now, even if other workers happen to be idle. The javadoc is explicit that core threads are the first answer.
- corePoolSize or more workers are running: queue the task instead of adding a thread, as long as the queue still has room. At this stage waiting beats growth on purpose.
- The queue is full and fewer than maximumPoolSize workers exist: create another worker and run the task on it. This is the only moment maximumPoolSize means anything.
- The queue is full and maximumPoolSize workers are running: hand the task to the rejection handler, which decides between throwing, running the task on the caller, or dropping it.
The queue fills before the pool grows, so growth to max only happens when the queue can fill.
core 2 · queue 3 · max 4
workers
queue (capacity 3, FIFO)
The pool is declared: core 2, max 4, and a queue that holds 3. No worker exists yet, because ThreadPoolExecutor starts threads on demand rather than in the constructor.
The classic misunderstanding: a max that never matters
Put the rule together with an unbounded queue and the consequence writes itself: if the queue never fills, stage three never runs, and no more than corePoolSize threads are ever created. The javadoc says it outright, an unbounded queue means maximumPoolSize does not have any effect. newFixedThreadPool(n) is exactly that shape, core and max both n with an unbounded LinkedBlockingQueue, so n is a hard concurrency limit and the queue absorbs everything else.
This is where the misunderstanding lives. A service is configured with max 200 and a thread dump shows 10 threads while the heap fills with queued tasks: the ceiling everyone read as protection is decoration, and the real bound is memory. When max must mean something, the queue has to be bounded, which makes the full state reachable and the rejection handler load-bearing.
One more nuance from the same javadoc: between core and max, a new thread is created only if the queue is full. Threads above core are the overflow zone, and they are the first to be retired by keepAliveTime once they sit idle.
Unbounded queue: maximumPoolSize is a comment, not a limit. The pool turns overload into queue growth, and the queue turns it into heap pressure.
ThreadPoolExecutor growth pipeline
core 2 · queue 3 · max 4, matching the board above
1tasks in
every submit walks the rule to the right, one branch at a time
2core threads
fewer than core running: create a worker right now, even if others idle
3bounded queue
core busy: tasks wait here in submission order, and capacity is the memory bound
4extra threads
queue full and below max: grow above core, and this is where maximumPoolSize lives
5rejection gate
queue full and at max: the handler decides, and doing nothing is not one of the options
The order is the rule: core threads, then the queue, then growth above core, then the rejection gate.
Bind the queue and the last two stages become reachable; leave it unbounded and stage 4 never opens, which is why maximumPoolSize so often means nothing at all.
The factories, decoded
Read every factory as a constructor call and its failure mode falls out of the parameters. The four below cover almost every pool in the wild; the scheduled executor has its own lesson, and work stealing has its own pool for reasons that lesson will explain.
| Factory | core / max | Queue | Failure mode |
|---|---|---|---|
| newFixedThreadPool(n) | n / n | unbounded LinkedBlockingQueue | queue growth masquerades as capacity; overload becomes memory |
| newCachedThreadPool() | 0 / Integer.MAX_VALUE, 60 s idle | SynchronousQueue | a burst creates a thread per task; the only shrinking is the idle timeout |
| newSingleThreadExecutor() | 1 / 1 | unbounded, wrapped so it cannot be reconfigured | serial by design; one slow task delays everything behind it |
| newWorkStealingPool() | ForkJoinPool at a target parallelism | per-worker deques with work stealing | tasks must stay short and forkable; execution order is unspecified |
- newFixedThreadPool reuses n threads off one shared queue: at most n tasks run at once, and the rest wait in submission order.
- newCachedThreadPool is thread-per-task with reuse: idle threads take the next task directly through the SynchronousQueue, and threads unused for 60 seconds are terminated. A burst above the reuse rate turns into thread creation.
- newSingleThreadExecutor guarantees sequential execution and replaces its worker if that worker dies, which makes it the right pick for a serialization point and the wrong one for parallelism.
- newWorkStealingPool is a ForkJoinPool behind the ExecutorService facade, for tasks that split into smaller tasks; order is unspecified, so keep sequencing out of it (see the ForkJoinPool lesson).
The factory name tells you the policy; the queue tells you the failure mode.
When both are full: the four rejection policies
The rejection handler fires exactly when the queue is full and every worker is at max, or when the pool has already been shut down. It is not an error path bolted on to the side; it is the pool's overflow contract, and ThreadPoolExecutor ships four implementations.
- AbortPolicy, the default, throws RejectedExecutionException to the submitter. Loud, local and honest: the caller learns the pool is saturated, and nothing is dropped silently.
- CallerRunsPolicy runs the task on the thread that called execute, which is the submitting thread. Under overload the producer slows down, which is backpressure applied at exactly the right place. If the pool is already shut down, the task is discarded instead.
- DiscardPolicy drops the task silently. It is legal only where losing work is genuinely acceptable, and a terrible policy to inherit by accident.
- DiscardOldestPolicy drops the head of the queue and retries, which for a FIFO queue means discarding the task that waited longest. Choose it when recency beats completeness, such as position updates or market data.
CallerRunsPolicy is backpressure you can feel at the call site; AbortPolicy is backpressure you have to catch.
Sizing: from the workload, not from superstition
Thread count is a capacity decision, and the honest starting point is what the tasks actually do. A CPU-bound task wants about as many threads as the machine has cores, Runtime.getRuntime().availableProcessors(), plus one as the classic comfort setting; more threads than cores buy context switches rather than throughput.
An I/O-bound task spends most of its life waiting, so more threads keep the cores fed, which makes the right number larger. It also makes it bounded and measured, because the resource being waited on has its own limit. That is the same argument the connection pools lesson makes about database connections: past a knee, more concurrent work makes throughput worse and latency climb, so size from a load test and read the queue depth as the signal that the size is wrong.
- CPU-bound: about the number of cores. Parallel computation is limited by cores, so that is the number worth starting from.
- I/O-bound: larger, bounded, measured. Threads waiting on sockets are only cheap next to the resource they are waiting for; find the knee by measurement, not by mood.
- The queue is part of the size. A bounded queue plus a rejection policy turns overload into an answer; an unbounded queue turns it into heap growth.
- Write the reasoning down. A comment that says three cores and two blocking waits per task survives the next refactor; a bare number does not.
Size from the shape of the work and one measurement; every other number is a guess with a confident tone.
The small controls that change behaviour
keepAliveTime is often misread as a global idle timeout. By default it applies to threads above core only, and core threads live indefinitely; allowCoreThreadTimeOut(true) extends the timeout to them, which is how a pool shrinks towards zero in quiet periods.
prestartAllCoreThreads() creates the core workers eagerly, trading init-time latency for a burst of thread creation at startup. The live counters are worth knowing because they become your metrics: getPoolSize, getActiveCount, getQueue().size() and getCompletedTaskCount each answer a different question about what the pool is doing.
One factory detail pays for itself during an incident. The default thread factory names threads pool-N-thread-M, which tells you which pool a thread belongs to and nothing about what it does. A factory that names workers order-worker-1 or batch-worker-3 turns a thread dump from a list into an explanation.
A thread dump is a debugging tool, and named threads turn it from a list into an explanation.
Remember
The rule in one breath: core threads first, then the queue, then growth above core once the queue is full, then the rejection handler once max is reached. The queue is what makes the middle steps possible, and its bound is what makes the last two reachable.
So read the queue before trusting the numbers on the config line. A bounded queue makes maximumPoolSize real; an unbounded queue makes it decoration, and moves the overload you were defending against into the heap.
A pool's behaviour is its queue's behaviour; choose the queue first.
The pool with maximumPoolSize 200 that ran 10 threads
A service is sized to max 200 to survive bursts and left on the default unbounded queue. Under overload the thread count stays at core, the queue grows into the millions, and the incident is an OutOfMemoryError on a pool that looked generous on paper. The fix is not a bigger max: give the pool a bounded queue, choose the rejection handler for the full case, CallerRunsPolicy is the built-in backpressure, and let the number you wrote finally mean what it says.
Interview angles
Walk through what happens when a task is submitted to a ThreadPoolExecutor.+
Fewer than core workers running: create one. At core or more: queue it, if there is room. Queue full and below max: create another worker. Queue full and at max: the rejection handler decides.
Core threads are preferred even when other workers are idle, and between core and max a new thread appears only when the queue is full. That ordering is the entire behaviour of the pool.
Why does maximumPoolSize often have no effect?+
Because the queue never fills. With an unbounded queue every task beyond core waits forever instead of triggering growth, and the javadoc states that the value has no effect. Bound the queue and max becomes reachable, with the rejection handler as the price of bounding it.
Common misconception: Raising maximumPoolSize is assumed to raise concurrency. With an unbounded queue it changes nothing at all.
How do newFixedThreadPool and newCachedThreadPool differ in practice?+
Fixed holds n threads behind one shared unbounded queue, so concurrency is exactly n and overload becomes queue growth. Cached has zero core threads and a SynchronousQueue, so every task must hand off to an idle thread or create a new one: bursts create threads, and 60 seconds of idleness retires them.
What does CallerRunsPolicy do, and when is it the right handler?+
It runs the rejected task on the thread that called execute, so the submitting side slows down and applies backpressure where the load originates. It is right when dropping work is unacceptable and slowing the producer is survivable. If the pool is already shut down, the task is discarded.
Follow-up: What does CallerRunsPolicy do to a web server whose request threads submit the tasks?
How do you size a thread pool?+
From the work: CPU-bound pools track the core count, I/O-bound pools go larger but stay bounded and get sized by measurement, and the queue bound plus rejection policy decide what happens beyond the size. The connection pools lesson makes the same argument one resource over.
The number that matters is how much concurrent work the resource behind the tasks can absorb, not how many threads you can create. Past that knee, extra threads convert into latency and failure.
A pool built on a SynchronousQueue rejects a task even though nothing is waiting in it. Why?+
Because a SynchronousQueue has no capacity: a task gets in only if a worker takes it at that instant. If every worker is busy, the handoff fails, so the pool either creates a thread (if below max) or rejects. Waiting for a slot is not something that queue offers.
Common misconception: An empty queue is assumed to be able to accept a task. With zero capacity, empty merely means nobody is waiting for one right now.