ThreadPoolExecutor
Executors.newFixedThreadPool and friends are thin wrappers over ThreadPoolExecutor, whose constructor exposes the settings that matter in production: how many threads, how large the queue, and what happens when both are full. The rule for when it adds threads surprises most people. This page traces it task by task, shows how the queue choice changes everything, runs each rejection policy, and measures how many threads CPU-bound work really needs.
Contents
How a ThreadPoolExecutor is built
java.util.concurrent.ThreadPoolExecutorExecutorServiceBlockingQueueAtomicIntegerctl
| Parameter | Meaning |
|---|---|
corePoolSize | Threads kept even when idle (unless allowCoreThreadTimeOut |
maximumPoolSize | The most threads the pool will ever create |
keepAliveTimeunit | How long a thread above the core size may stay idle before it ends |
workQueue | Where tasks wait when the core threads are busy |
threadFactory | Creates the threads: names, daemon flag, exception handler |
handler | The RejectedExecutionHandler |
The Javadoc of execute
- If fewer than
threads are running, start a new thread with this task, even if other threads are idle.corePoolSize - Otherwise, try to put the task in the queue.
- If the queue is full, start a new thread, as long as there are fewer than
.maximumPoolSize - Otherwise, reject the task.
The surprise is step 2 before step 3: the pool prefers queueing to growing. It only adds threads beyond the core size when the queue is full. With an unbounded queue, that never happens. The examples were run on JDK 21 on a 2-CPU machine.
Tracing the growth rule
A pool with core 2, maximum 4 and a queue of 3 receives 8 tasks that all block until released, so nothing finishes during the experiment and each step is visible.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class GrowthRules {
public static void main(String[] args) throws InterruptedException {
// core 2, max 4, queue of 3: watch where each task goes
ThreadPoolExecutor pool = new ThreadPoolExecutor(
2, 4, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3));
CountDownLatch release = new CountDownLatch(1);
Runnable blocker = () -> {
try {
release.await(); // keep every worker busy until released
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
for (int task = 1; task <= 8; task++) {
try {
pool.execute(blocker);
System.out.printf("task %d accepted: threads=%d, queued=%d%n",
task, pool.getPoolSize(), pool.getQueue().size());
} catch (RejectedExecutionException e) {
System.out.printf("task %d REJECTED: threads=%d (max), queue full%n",
task, pool.getPoolSize());
}
}
release.countDown();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("completed tasks: " + pool.getCompletedTaskCount());
}
}
Output:
task 1 accepted: threads=1, queued=0
task 2 accepted: threads=2, queued=0
task 3 accepted: threads=2, queued=1
task 4 accepted: threads=2, queued=2
task 5 accepted: threads=2, queued=3
task 6 accepted: threads=3, queued=3
task 7 accepted: threads=4, queued=3
task 8 REJECTED: threads=4 (max), queue full
completed tasks: 7
- Tasks 1 and 2 each started a core thread. A new pool has no threads at all; core threads are created as tasks arrive.
- Tasks 3 to 5 went into the queue, although the pool was allowed 2 more threads. Only when the queue was full did tasks 6 and 7 get new threads, up to the maximum of 4.
- Task 8 found 4 threads and a full queue, so the default
threwAbortPolicy . The capacity isRejectedExecutionException + queue capacity: 4 + 3 = 7 tasks.maximumPoolSize - Note the order of execution this creates: tasks 6 and 7 started before tasks 3 to 5, which were still queued. A thread-pool queue is not a strict first come, first served line once extra threads are added.
The queue decides how the pool behaves
Because of the growth rule, the queue type matters more than the size settings. The program gives three pools the same core 2 and maximum 10 and submits 1,000 blocking tasks to each.
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.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class QueueChoice {
public static void main(String[] args) throws InterruptedException {
// Same pool settings (core 2, max 10), three different queues, 1,000 blocked tasks
run("unbounded LinkedBlockingQueue", new LinkedBlockingQueue<>());
run("ArrayBlockingQueue(100)", new ArrayBlockingQueue<>(100));
run("SynchronousQueue", new SynchronousQueue<>());
}
static void run(String name, BlockingQueue<Runnable> queue) throws InterruptedException {
ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 10, 30, TimeUnit.SECONDS, queue);
CountDownLatch release = new CountDownLatch(1);
int rejected = 0;
for (int i = 0; i < 1000; i++) {
try {
pool.execute(() -> {
try {
release.await(); // keep every thread busy
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
} catch (RejectedExecutionException e) {
rejected++;
}
}
System.out.printf("%-30s threads %2d, queued %4d, rejected %4d%n",
name, pool.getPoolSize(), pool.getQueue().size(), rejected);
release.countDown();
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}
Output:
unbounded LinkedBlockingQueue threads 2, queued 998, rejected 0
ArrayBlockingQueue(100) threads 10, queued 100, rejected 890
SynchronousQueue threads 10, queued 0, rejected 990
- With an unbounded
, the pool never grew past its 2 core threads, and 998 tasks waited.LinkedBlockingQueue had no effect at all. This is howmaximumPoolSize is built, and why it can collect millions of waiting tasks and run out of memory under load.newFixedThreadPool - With an
of 100, the pool filled the queue, grew to 10 threads, and rejected the remaining 890. Of the three, this is the only configuration in which the queue, the thread count and the rejection all do something.ArrayBlockingQueue - A
holds nothing, so every task needed a free thread: 10 ran and 990 were rejected.SynchronousQueue uses this queue with a maximum ofnewCachedThreadPool , which means it never rejects but may create a thread per task.Integer.MAX_VALUE
| Queue | Threads beyond core | Rejects | Risk |
|---|---|---|---|
Unbounded LinkedBlockingQueue | Never | Never | Unbounded memory and latency |
Bounded ArrayBlockingQueueLinkedBlockingQueue(n) | When the queue is full | When threads and queue are full | Must handle rejection |
SynchronousQueue | Whenever no thread is idle | At the maximum | Many threads if the maximum is large |
PriorityBlockingQueue | Never (unbounded) | Never | Tasks must be comparable; use executesubmitFutureTask |
Rejection policies
When a task cannot be accepted, the pool calls its RejectedExecutionHandlerThreadPoolExecutor
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class Policies {
// 1 thread + 1 queue slot; 3 tasks arrive at once, so task 3 does not fit
static String run(RejectedExecutionHandler policy) throws InterruptedException {
List<String> outcome = Collections.synchronizedList(new ArrayList<>());
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1), Thread.ofPlatform().name("worker").factory(),
policy);
for (int i = 1; i <= 3; i++) {
int id = i;
try {
pool.execute(() -> {
sleep(100);
outcome.add("task" + id + "@" + Thread.currentThread().getName());
});
} catch (RejectedExecutionException e) {
outcome.add("task" + id + " threw " + e.getClass().getSimpleName());
}
}
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
List<String> sorted = new ArrayList<>(outcome);
Collections.sort(sorted);
return sorted.toString();
}
public static void main(String[] args) throws InterruptedException {
System.out.printf("%-20s %s%n", "AbortPolicy", run(new ThreadPoolExecutor.AbortPolicy()));
System.out.printf("%-20s %s%n", "CallerRunsPolicy",
run(new ThreadPoolExecutor.CallerRunsPolicy()));
System.out.printf("%-20s %s%n", "DiscardPolicy",
run(new ThreadPoolExecutor.DiscardPolicy()));
System.out.printf("%-20s %s%n", "DiscardOldestPolicy",
run(new ThreadPoolExecutor.DiscardOldestPolicy()));
// A custom handler: count and log, so rejections are visible in metrics
AtomicInteger rejected = new AtomicInteger();
System.out.printf("%-20s %s, counted %d%n", "custom (log+count)", run((r, executor) -> {
rejected.incrementAndGet();
System.out.println(" custom handler: rejected, queue size "
+ executor.getQueue().size());
}), rejected.get());
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
AbortPolicy [task1@worker, task2@worker, task3 threw RejectedExecutionException]
CallerRunsPolicy [task1@worker, task2@worker, task3@main]
DiscardPolicy [task1@worker, task2@worker]
DiscardOldestPolicy [task1@worker, task3@worker]
custom handler: rejected, queue size 1
custom (log+count) [task1@worker, task2@worker], counted 1
, the default, threwAbortPolicy for task 3. The caller learns about the overload immediately, which is usually what you want.RejectedExecutionException ran task 3 onCallerRunsPolicy , the thread that submitted it. While the caller is busy running a task, it cannot submit more, so this policy slows producers down automatically. It is a simple form of backpressure, at the cost of the caller's latency.main dropped task 3 silently. Nothing in the output mentions it.DiscardPolicy dropped task 2, the oldest waiting task, and queued task 3 instead. That suits data where only the newest value matters, such as sensor readings, and is dangerous for anything else.DiscardOldestPolicy- A custom handler is a lambda. This one counted and logged the rejection, then dropped the task. Logging or counting rejections in metrics is the minimum for production pools. The two discard policies also leave any
fromFuture forever incomplete, so a caller waiting on it hangs.submit
Keep-alive, core time-out and pre-starting
Threads above the core size end after being idle for keepAliveTime
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class KeepAlive {
public static void main(String[] args) throws InterruptedException {
// core 1, max 3, idle extra threads end after 200 ms
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 3, 200, TimeUnit.MILLISECONDS,
new SynchronousQueue<>());
System.out.println("new pool: threads " + pool.getPoolSize());
for (int i = 0; i < 3; i++) {
pool.execute(() -> sleep(100));
}
System.out.println("during a burst of 3: threads " + pool.getPoolSize());
Thread.sleep(600);
System.out.println("600 ms after the burst: threads " + pool.getPoolSize()
+ " (largest was " + pool.getLargestPoolSize() + ")");
pool.allowCoreThreadTimeOut(true); // core threads may time out too
Thread.sleep(400);
System.out.println("allowCoreThreadTimeOut: threads " + pool.getPoolSize());
pool.shutdown();
// Core threads are normally created lazily, one per submitted task
ThreadPoolExecutor warm = new ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS,
new LinkedBlockingQueue<>());
System.out.println("fixed pool before tasks: threads " + warm.getPoolSize());
System.out.println("prestartAllCoreThreads(): started " + warm.prestartAllCoreThreads()
+ ", threads " + warm.getPoolSize());
warm.shutdown();
warm.awaitTermination(1, TimeUnit.SECONDS);
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
new pool: threads 0
during a burst of 3: threads 3
600 ms after the burst: threads 1 (largest was 3)
allowCoreThreadTimeOut: threads 0
fixed pool before tasks: threads 0
prestartAllCoreThreads(): started 4, threads 4
- The burst grew the pool from 0 to 3 threads. 600 ms later, the two extra threads had been idle for more than 200 ms and had ended, leaving the 1 core thread;
still remembers 3.getLargestPoolSize applies the keep-alive to core threads too, and the pool went down to 0 threads. That suits pools that are idle most of the time, such as a nightly job's pool in a long-running service.allowCoreThreadTimeOut(true)- A new pool starts with no threads, so the first tasks pay for creating them.
created all 4 core threads at once and returned 4, which is useful before a latency-sensitive burst.prestartAllCoreThreads
Hooks and monitoring
ThreadPoolExecutorbeforeExecuteafterExecuteterminatedsubmitexecute
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class HooksAndStats {
// A pool that times every task and logs every failure
static class MonitoredPool extends ThreadPoolExecutor {
final AtomicLong failures = new AtomicLong();
private final ThreadLocal<Long> startedAt = new ThreadLocal<>();
MonitoredPool(int threads) {
super(threads, threads, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
Thread.ofPlatform().name("pool-", 1).uncaughtExceptionHandler((th, e) ->
System.out.println(" a worker thread died: " + e)).factory());
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
startedAt.set(System.nanoTime());
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
long ms = (System.nanoTime() - startedAt.get()) / 1000000;
Throwable failure = t;
// submit() wraps tasks in a FutureTask, which catches the exception itself,
// so t is null; the failure has to be read from the Future
if (failure == null && r instanceof Future<?> f && f.isDone()) {
try {
f.get();
} catch (ExecutionException e) {
failure = e.getCause();
} catch (CancellationException | InterruptedException e) {
failure = e;
}
}
if (failure != null) {
failures.incrementAndGet();
System.out.println(" afterExecute: failed after ~" + ms / 50 * 50 + " ms: "
+ failure.getMessage() + " (t was " + (t == null ? "null" : "set") + ")");
}
}
}
public static void main(String[] args) throws InterruptedException {
MonitoredPool pool = new MonitoredPool(2);
for (int i = 1; i <= 5; i++) {
int id = i;
pool.submit(() -> {
sleep(100);
if (id == 3) {
throw new IllegalStateException("task 3 broke");
}
});
}
pool.execute(() -> {
throw new IllegalArgumentException("execute broke");
});
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
System.out.println("taskCount " + pool.getTaskCount()
+ ", completedTaskCount " + pool.getCompletedTaskCount()
+ ", largestPoolSize " + pool.getLargestPoolSize()
+ ", failures " + pool.failures.get());
}
static void sleep(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Output:
afterExecute: failed after ~100 ms: task 3 broke (t was null)
afterExecute: failed after ~0 ms: execute broke (t was set)
a worker thread died: java.lang.IllegalArgumentException: execute broke
taskCount 6, completedTaskCount 6, largestPoolSize 2, failures 2
- For the submitted task,
receivedafterExecute even though the task threw.t == null wraps the task in asubmit , which catches the exception and stores it, so the hook must read it from the future, as this code does. Many hand-written monitoring hooks miss exactly this case.FutureTask - For the
task,execute was set. The exception then left the worker, the thread died, and its uncaught exception handler ran; the pool started a replacement thread.t (6),getTaskCount (6, which counts failed tasks too) andgetCompletedTaskCount (2) are approximate while the pool is running, but exact after termination. Export them, together withgetLargestPoolSize andgetQueue().size() , to your monitoring system.getActiveCount- The
holding the start time works becauseThreadLocal andbeforeExecute run on the same worker thread as the task.afterExecute
How many threads?
Sixteen tasks that each count primes below 300,000, pure CPU work with no waiting, run on pools of 1, 2, 4 and 16 threads. The machine has 2 CPUs. Each size runs 3 times and the fastest run is reported; this is a rough comparison, not a benchmark.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Sizing {
// Pure CPU work: count primes below a limit by trial division
static int primesBelow(int limit) {
int count = 0;
for (int n = 2; n < limit; n++) {
boolean prime = true;
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) {
prime = false;
break;
}
}
if (prime) {
count++;
}
}
return count;
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("availableProcessors = " + cores + "; 16 CPU-bound tasks, best of 3");
for (int threads : new int[] {1, 2, 4, 16}) {
long best = Long.MAX_VALUE;
int total = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
try (ExecutorService pool = Executors.newFixedThreadPool(threads)) {
List<Future<Integer>> fs = new ArrayList<>();
for (int i = 0; i < 16; i++) {
fs.add(pool.submit(() -> primesBelow(300000)));
}
total = 0;
for (Future<Integer> f : fs) {
total += f.get();
}
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%2d threads: %,5d ms (primes counted %,d)%n",
threads, best / 1000000, total);
}
}
}
Output (2-CPU Linux machine running JDK 21):
availableProcessors = 2; 16 CPU-bound tasks, best of 3
1 threads: 323 ms (primes counted 415,952)
2 threads: 160 ms (primes counted 415,952)
4 threads: 160 ms (primes counted 415,952)
16 threads: 164 ms (primes counted 415,952)
- Going from 1 to 2 threads roughly halved the time. Going from 2 to 4 or 16 changed almost nothing: with 2 cores, at most 2 threads can compute at any moment, and the extra threads only take turns.
- For CPU-bound work, size the pool at
, perhaps plus one. More threads add memory and context switching without adding speed. Inside containers,availableProcessors() reflects the CPU limit since Java 10.availableProcessors() - For tasks that wait, a common estimate from Java Concurrency in Practice is cores × (1 + wait time / compute time). A task that waits 90 ms for every 10 ms of CPU on 2 cores suggests 2 × 10 = 20 threads. Since Java 21, the simpler answer for waiting tasks is often virtual threads; see
ExecutorService .
Choosing pool settings
| Goal | Configuration |
|---|---|
| CPU-bound work with backpressure | core = max = cores, bounded ArrayBlockingQueueCallerRunsPolicy |
| Bursty work that should grow, then shrink | core small, max larger, bounded queue, keep-alive of 30 to 60 s |
| Fail fast under overload | Bounded queue with AbortPolicy |
| Only the latest value matters | Small queue with DiscardOldestPolicy |
| Rarely used pool | allowCoreThreadTimeOut(true) |
| Latency-sensitive start | prestartAllCoreThreads() |
| Metrics and failure logging | Subclass with afterExecuteFuture |
| Many tasks that wait on I/O | Executors.newVirtualThreadPerTaskExecutor() |
Always give pools a ThreadFactory