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.ThreadPoolExecutor (Java 5) is the class behind most ExecutorService instances. It keeps a set of worker threads; each worker runs its first task and then loops, taking further tasks from a BlockingQueue until the pool shuts down or the worker has been idle too long. The pool's state and its worker count are packed into one AtomicInteger called ctl: the top 3 bits hold the run state (RUNNING, SHUTDOWN, STOP, TIDYING, TERMINATED) and the low 29 bits the number of workers, so both can be changed together with one compare-and-set.

The constructor parameters
ParameterMeaning
corePoolSizeThreads kept even when idle (unless allowCoreThreadTimeOut is set)
maximumPoolSizeThe most threads the pool will ever create
keepAliveTime, unitHow long a thread above the core size may stay idle before it ends
workQueueWhere tasks wait when the core threads are busy
threadFactoryCreates the threads: names, daemon flag, exception handler
handlerThe RejectedExecutionHandler called when a task cannot be accepted

The Javadoc of execute describes the rule that decides where a new task goes, in this order:

  1. If fewer than corePoolSize threads are running, start a new thread with this task, even if other threads are idle.
  2. Otherwise, try to put the task in the queue.
  3. If the queue is full, start a new thread, as long as there are fewer than maximumPoolSize.
  4. 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.

Java
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:

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 AbortPolicy threw RejectedExecutionException. The capacity is maximumPoolSize + queue capacity: 4 + 3 = 7 tasks.
  • 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.

Java
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:

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 LinkedBlockingQueue, the pool never grew past its 2 core threads, and 998 tasks waited. maximumPoolSize had no effect at all. This is how newFixedThreadPool is built, and why it can collect millions of waiting tasks and run out of memory under load.
  • With an ArrayBlockingQueue 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.
  • A SynchronousQueue holds nothing, so every task needed a free thread: 10 ran and 990 were rejected. newCachedThreadPool uses this queue with a maximum of Integer.MAX_VALUE, which means it never rejects but may create a thread per task.
Queue types and their effect
QueueThreads beyond coreRejectsRisk
Unbounded LinkedBlockingQueueNeverNeverUnbounded memory and latency
Bounded ArrayBlockingQueue or LinkedBlockingQueue(n)When the queue is fullWhen threads and queue are fullMust handle rejection
SynchronousQueueWhenever no thread is idleAt the maximumMany threads if the maximum is large
PriorityBlockingQueueNever (unbounded)NeverTasks must be comparable; use execute, since submit wraps tasks in an incomparable FutureTask

Rejection policies

When a task cannot be accepted, the pool calls its RejectedExecutionHandler. The JDK has four, nested in ThreadPoolExecutor. Each run below uses 1 thread and a queue of 1 and submits 3 tasks of 100 ms at once, so task 1 runs, task 2 waits and task 3 does not fit. The results are sorted so that thread timing cannot change the order.

Java
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:

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
  • AbortPolicy, the default, threw RejectedExecutionException for task 3. The caller learns about the overload immediately, which is usually what you want.
  • CallerRunsPolicy ran task 3 on main, 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.
  • DiscardPolicy dropped task 3 silently. Nothing in the output mentions it.
  • DiscardOldestPolicy 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.
  • 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 Future from submit forever incomplete, so a caller waiting on it hangs.

Keep-alive, core time-out and pre-starting

Threads above the core size end after being idle for keepAliveTime. The pool below has core 1, maximum 3 and a 200 ms keep-alive, and receives a burst of 3 tasks; then the program changes the settings that control idle and initial threads.

Java
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:

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; getLargestPoolSize still remembers 3.
  • allowCoreThreadTimeOut(true) 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.
  • A new pool starts with no threads, so the first tasks pay for creating them. prestartAllCoreThreads created all 4 core threads at once and returned 4, which is useful before a latency-sensitive burst.

Hooks and monitoring

ThreadPoolExecutor has three protected methods meant for subclasses: beforeExecute, afterExecute and terminated. They are the place for timing, logging and metrics. The pool below times each task and reports failures; five tasks are submitted with submit, task 3 of which throws, and one with execute.

Java
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:

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, afterExecute received t == null even though the task threw. submit wraps the task in a FutureTask, 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.
  • For the execute task, t was set. The exception then left the worker, the thread died, and its uncaught exception handler ran; the pool started a replacement thread.
  • getTaskCount (6), getCompletedTaskCount (6, which counts failed tasks too) and getLargestPoolSize (2) are approximate while the pool is running, but exact after termination. Export them, together with getQueue().size() and getActiveCount, to your monitoring system.
  • The ThreadLocal holding the start time works because beforeExecute and afterExecute run on the same worker thread as the task.

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.

Java
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):

Output
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 availableProcessors(), perhaps plus one. More threads add memory and context switching without adding speed. Inside containers, availableProcessors() reflects the CPU limit since Java 10.
  • 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

Recommended ThreadPoolExecutor configurations
GoalConfiguration
CPU-bound work with backpressurecore = max = cores, bounded ArrayBlockingQueue, CallerRunsPolicy
Bursty work that should grow, then shrinkcore small, max larger, bounded queue, keep-alive of 30 to 60 s
Fail fast under overloadBounded queue with AbortPolicy, and handle the exception (for example, HTTP 503)
Only the latest value mattersSmall queue with DiscardOldestPolicy
Rarely used poolallowCoreThreadTimeOut(true)
Latency-sensitive startprestartAllCoreThreads()
Metrics and failure loggingSubclass with afterExecute that also checks the Future
Many tasks that wait on I/OExecutors.newVirtualThreadPerTaskExecutor() instead of a pool

Always give pools a ThreadFactory that names their threads, so thread dumps show which pool is stuck. For the queues themselves, see BlockingQueue; for recursive tasks, see ForkJoinPool.