ThreadPoolExecutor in Java: Core and Maximum Size, Work Queues and Rejection Policies
How ThreadPoolExecutor really decides between starting a thread, queuing a task and rejecting it. Core and maximum sizes, keep-alive, why an unbounded queue makes the maximum useless, the four rejection policies, what each Executors factory builds, and sizing rules for CPU and I/O work.
kvi5hnuCode Sprout team member8 min readOn this page
Article 19's MiniPool had a fixed number of threads and one bounded queue. java.util.concurrent.ThreadPoolExecutor, the class behind most of the Executors factory methods, adds elastic sizing, a choice of queues and configurable overload handling. Its constructor has seven parameters, and the way they interact surprises many developers. This article makes the behavior concrete.
The parameters
new ThreadPoolExecutor(
corePoolSize, // threads kept even when idle
maximumPoolSize, // upper limit on threads
keepAliveTime, // how long an idle thread above the core waits before exiting
unit, // the unit of keepAliveTime
workQueue, // where tasks wait for a thread
threadFactory, // optional: how threads are created (names, daemon flag)
handler); // optional: what to do when the pool can't accept a task
Two more settings are available through methods: allowCoreThreadTimeOut(true) lets even core threads exit after the keep-alive time, and prestartAllCoreThreads() starts the core threads before the first task arrives. By default, threads are created lazily, one per task, until the core size is reached.
The order of decisions
When you call execute(task) (or submit, which wraps the task in a Future and calls execute), the executor follows these steps in order:

- Fewer than
corePoolSizethreads? Start a new thread for this task, even if other threads are idle. - Otherwise, offer the task to the queue.
- If the queue refuses (it's full) and fewer than
maximumPoolSizethreads exist, start an extra thread for this task. - Otherwise, reject the task by calling the rejection handler.
The important detail is step 2 before step 3: the pool grows beyond the core size only when the queue is full. Many people expect the opposite ("use up to max threads, then queue").
Watching it decide
The program builds pools with core 2, maximum 4 and a 200 ms keep-alive, and submits tasks that block until released, reporting what the pool did after each one:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Solution {
/** Submits 'tasks' tasks that all wait for 'release', reporting what the pool did with each. */
static ThreadPoolExecutor fill(String title, BlockingQueue<Runnable> queue, RejectedExecutionHandler policy,
int tasks, CountDownLatch release) {
System.out.println(title);
ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 4, 200, TimeUnit.MILLISECONDS, queue, policy);
List<String> report = new ArrayList<>();
for (int i = 1; i <= tasks; i++) {
int id = i;
try {
pool.execute(() -> {
if (!Thread.currentThread().getName().startsWith("pool")) {
report.add("task " + id + " ran in the caller (" + Thread.currentThread().getName() + ")");
return;
}
try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
report.add("task " + id + ": threads=" + pool.getPoolSize() + ", queued=" + pool.getQueue().size());
} catch (RejectedExecutionException e) {
report.add("task " + id + ": REJECTED");
}
}
report.forEach(line -> System.out.println(" " + line));
return pool;
}
public static void main(String[] args) throws InterruptedException {
// 1. Bounded queue: core threads first, then the queue, then extra threads, then rejection
CountDownLatch release = new CountDownLatch(1);
ThreadPoolExecutor pool = fill("core 2, max 4, ArrayBlockingQueue(2), AbortPolicy:",
new ArrayBlockingQueue<>(2), new ThreadPoolExecutor.AbortPolicy(), 8, release);
release.countDown();
Thread.sleep(600); // idle longer than keepAlive (200 ms)
System.out.println(" after the burst and 600 ms idle: threads=" + pool.getPoolSize()
+ ", completed=" + pool.getCompletedTaskCount());
pool.close();
// 2. Unbounded queue: the maximum is never used
CountDownLatch release2 = new CountDownLatch(1);
ThreadPoolExecutor unbounded = fill("core 2, max 4, unbounded LinkedBlockingQueue:",
new LinkedBlockingQueue<>(), new ThreadPoolExecutor.AbortPolicy(), 8, release2);
release2.countDown();
unbounded.close();
// 3. CallerRunsPolicy: when full, the submitting thread runs the task itself
CountDownLatch release3 = new CountDownLatch(1);
ThreadPoolExecutor callerRuns = fill("core 2, max 4, ArrayBlockingQueue(2), CallerRunsPolicy:",
new ArrayBlockingQueue<>(2), new ThreadPoolExecutor.CallerRunsPolicy(), 7, release3);
release3.countDown();
callerRuns.close();
}
}
Output:
core 2, max 4, ArrayBlockingQueue(2), AbortPolicy:
task 1: threads=1, queued=0
task 2: threads=2, queued=0
task 3: threads=2, queued=1
task 4: threads=2, queued=2
task 5: threads=3, queued=2
task 6: threads=4, queued=2
task 7: REJECTED
task 8: REJECTED
after the burst and 600 ms idle: threads=2, completed=6
core 2, max 4, unbounded LinkedBlockingQueue:
task 1: threads=1, queued=0
task 2: threads=2, queued=0
task 3: threads=2, queued=1
task 4: threads=2, queued=2
task 5: threads=2, queued=3
task 6: threads=2, queued=4
task 7: threads=2, queued=5
task 8: threads=2, queued=6
core 2, max 4, ArrayBlockingQueue(2), CallerRunsPolicy:
task 1: threads=1, queued=0
task 2: threads=2, queued=0
task 3: threads=2, queued=1
task 4: threads=2, queued=2
task 5: threads=3, queued=2
task 6: threads=4, queued=2
task 7 ran in the caller (main)
task 7: threads=4, queued=2
- Bounded queue. Tasks 1–2 started core threads, 3–4 filled the queue, and only then did tasks 5–6 start extra threads, up to the maximum of 4. Tasks 7–8 found everything full and were rejected. After the burst, the two extra threads sat idle for longer than the keep-alive time and exited, leaving the core 2.
- Unbounded queue. The queue never refuses a task, so step 3 never happens. With 8 tasks waiting, the pool still has only 2 threads, and
maximumPoolSizehas no effect at all. This is howExecutors.newFixedThreadPoolworks on purpose, but it's a common bug when someone setsmaxto 50 and expects it to matter. - Caller runs. Instead of rejecting task 7, the pool ran it on the submitting thread,
main. Whilemainis busy running a task it can't submit more, which slows the producer down. That's a simple form of backpressure.
Choosing a work queue
| Queue | Behavior | Typical use |
|---|---|---|
ArrayBlockingQueue(n) / LinkedBlockingQueue(n) | bounded: holds up to n tasks, then the pool grows to max, then rejects | most production pools: overload becomes visible |
LinkedBlockingQueue() (no capacity) | unbounded: the pool stays at core size, and tasks queue without limit | newFixedThreadPool, newSingleThreadExecutor. Risk: memory grows under overload |
SynchronousQueue | no storage: a task is handed directly to a free thread, or a new thread is started, up to max | newCachedThreadPool (core 0, max unlimited) |
PriorityBlockingQueue | unbounded, ordered by priority instead of arrival | rarely, for priority-ordered jobs |
Rejection policies
When the queue is full and the pool is at maximum, or the pool has been shut down, the handler decides:
| Policy | What happens |
|---|---|
AbortPolicy (default) | execute throws RejectedExecutionException |
CallerRunsPolicy | the submitting thread runs the task itself (unless the pool is shut down, in which case the task is dropped) |
DiscardPolicy | the task is silently dropped |
DiscardOldestPolicy | the oldest queued task is dropped and the new one is retried |
The two "discard" policies lose work without telling anyone. Use them only for work that's truly optional, such as a metrics sample, and count what they drop. You can also implement RejectedExecutionHandler yourself, for example to log, record a metric and then throw.
What the factory methods build
| Factory method | Configuration |
|---|---|
newFixedThreadPool(n) | core = max = n, unbounded LinkedBlockingQueue |
newSingleThreadExecutor() | core = max = 1, unbounded queue, wrapped so it can't be reconfigured |
newCachedThreadPool() | core 0, max Integer.MAX_VALUE, 60 s keep-alive, SynchronousQueue |
newScheduledThreadPool(n) | a ScheduledThreadPoolExecutor with n core threads and a delay queue |
newWorkStealingPool() | not a ThreadPoolExecutor: a ForkJoinPool with parallelism = cores (article 22) |
newVirtualThreadPerTaskExecutor() | not a pool: one new virtual thread per task |
Note the two extremes. The fixed pool can't run out of threads but can run out of memory (unbounded queue). The cached pool can't queue but can run out of threads, since every task in a burst gets a new one. Frameworks such as Spring's ThreadPoolTaskExecutor expose the same parameters with safer defaults, so check what they're set to.
Sizing
- CPU-bound tasks: about one thread per core (
Runtime.getRuntime().availableProcessors()), perhaps plus one. More threads only add context switches. - Blocking tasks on platform threads: more threads than cores, estimated with Little's Law or the formula cores × (1 + wait time / compute time) (article 10), then confirmed by load testing.
- Blocking tasks on Java 21+: usually no pool at all: a virtual thread per task, with explicit limits on the scarce resources.
Monitor getActiveCount(), getQueue().size(), getCompletedTaskCount() and rejection counts. Override beforeExecute and afterExecute to time tasks or catch exceptions from tasks passed to execute. For tasks passed to submit, the exception stays in the Future and afterExecute receives null; check r instanceof Future<?> f && f.isDone() and call f.get() to see it, as the afterExecute javadoc shows.
What's current
- Since Java 19,
ExecutorService.close()performs an orderly shutdown and waits for termination.ThreadPoolExecutorinherits it, so pools work in try-with-resources. ThreadPoolExecutorhasn't changed in behavior for many releases. Its decision order is the same as in Java 5.- For blocking work, the JDK's guidance since Java 21 is to prefer virtual threads over tuning pools. For CPU-bound work and controlled parallelism, these pools remain the right tool.
Common questions
Why doesn't the pool use the maximum number of threads before queuing?
That's the documented design: it treats the core size as the normal number of threads and the queue as the buffer for bursts, and grows only when the buffer overflows. To prefer threads over queuing, use a SynchronousQueue (as the cached pool does), or set core = max with allowCoreThreadTimeOut(true).
What happens to tasks rejected because the pool is shut down?
They go to the same rejection handler. With the default AbortPolicy, execute throws RejectedExecutionException, which is what you want after shutdown.
shutdown() or shutdownNow()?
shutdown() stops accepting tasks and lets queued and running tasks finish. shutdownNow() also interrupts running tasks and returns the tasks that never started. Call awaitTermination (or close()) to wait for the result.
Can I change the size of a running pool?
Yes. setCorePoolSize and setMaximumPoolSize work at run time, which some applications use for tuning. Increases take effect at once, and surplus threads exit when they next become idle. Keep core ≤ max at every step: to grow both, raise the maximum first, or setCorePoolSize throws IllegalArgumentException. The executor returned by newSingleThreadExecutor doesn't allow it.
Summary
ThreadPoolExecutordecides in a fixed order: core threads, then the queue, then extra threads up to the maximum, then rejection.- The pool grows past the core size only when the queue is full, so with an unbounded queue the maximum is ignored.
- Idle threads above the core exit after
keepAliveTime. Core threads stay unlessallowCoreThreadTimeOutis set. - Choose the queue deliberately: bounded for visible overload,
SynchronousQueuefor direct hand-off, unbounded only when memory growth is acceptable. - Rejection policies abort (default), run in the caller (backpressure), or discard silently.
- Size CPU pools by cores, and blocking pools by measurement, or use virtual threads for blocking work.
Practice questions
A pool is created with new ThreadPoolExecutor(10, 100, 60, SECONDS, new LinkedBlockingQueue<>()). Under heavy load, monitoring shows exactly 10 active threads and a growing queue. Why, and how would you change it?
Answer
The queue is unbounded, so it always accepts tasks and the pool never grows past the core size of 10. The maximum of 100 is never used. Use a bounded queue (for example new ArrayBlockingQueue<>(500)), so the pool grows when it fills, or raise the core size if 10 is simply too small.
With core 2, max 3, ArrayBlockingQueue(1) and the default policy, six long-running tasks are submitted. What happens to each?
Answer
Tasks 1–2 start core threads, task 3 waits in the queue, task 4 starts the third (extra) thread, and tasks 5 and 6 are rejected with RejectedExecutionException.
Why can Executors.newCachedThreadPool() be dangerous for a server that receives a sudden burst of 20,000 slow requests?
Answer
It has a SynchronousQueue and no thread limit, so every request that finds no idle thread starts a new platform thread: up to 20,000 OS threads, each with its own stack. That can exhaust memory or the OS thread limit. A bounded pool, or virtual threads with explicit resource limits, avoid this.
Previous: Building a Thread Pool From Scratch in Java: Worker Threads and a Task Queue
Next: Callable and Future in Java: Task Results, Timeouts, Cancellation and invokeAll

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.