Executors & Thread Pools: Sizing the Old World

The on-call phone buzzed at 2 a.m. The order service was down, and the thread count graph told the story before anyone opened a log: 11,000 threads and climbing. A downstream pricing API had slowed from 40 ms to 4 seconds, and every incoming request was spawning work on a newCachedThreadPool(). Each stuck request held a thread; each new request created another. The pool did exactly what it was designed to do — create threads without limit — and the JVM fell over sideways.

The same month gave us a quieter wound. A deploy pipeline started hanging: the new version would start, the old one would never die. The culprit was a scheduled-report pool nobody shut down. Its worker threads were non-daemon, so the JVM sat there forever, politely refusing to exit, waiting for threads that would never get another task. The fix was three lines: shutdown(), awaitTermination(), done.

Both incidents are about the same thing: the lifecycle and shape of your threads, not the code the threads run. In the last post we met raw Thread objects and the JVM's threading model. This post is about the machinery the entire pre-virtual-thread Java world was built on — ExecutorService and thread pools: what the factory methods actually build, how to size a pool for CPU-bound vs IO-bound work (with real measurements), what happens when a pool fills up, and how to shut one down without hanging a deploy. The next post changes the game; this one makes sure you understand the game being changed.

Everything below ran on JDK 21.0.3 on a 2-vCPU Linux VM (Runtime.getRuntime().availableProcessors() == 2 — I'll say "2 cores" from here on). All timings are real, measured with System.nanoTime().

1. Anatomy of an ExecutorService: queue, workers, policy

A thread pool is three things, and keeping them separate in your head prevents most sizing mistakes:

The work queue holds submitted tasks that no worker has picked up yet. It's a BlockingQueue<Runnable> — usually unbounded (dangerous, you'll see why) or bounded (better, section 5).

The workers are long-lived threads that loop forever: take a task from the queue, run it, repeat. Creating a thread is not free — it reserves stack memory and asks the OS for a native thread — so the pool reuses workers instead of creating a thread per task.

The saturation policy decides what happens when every worker is busy and the queue is full. This is the part most developers never configure, and the default choice (throw an exception) surprises people at 2 a.m.

Submitter thread pool.submit(task) pool.execute(task) your request thread, never runs the task itself Work queue BlockingQueue<Runnable> tasks waiting for a worker unbounded = silent OOM risk Worker threads × N worker-1 → running task worker-2 → running task worker-3 → idle, parked long-lived, reused; loop: take → run → repeat N fixed, or grows to a max tasks flow this way Queue full? saturation policy fires: AbortPolicy (throw) CallerRunsPolicy DiscardPolicy DiscardOldestPolicy overflow The three questions that define any pool: how many workers, how big a queue, and what to do when both are full.

Hold that diagram. Every factory method, sizing rule, and incident in this post is a different answer to those three questions.

2. The factory methods: what they actually build

Executors gives you four famous one-liners. The names are friendly; the constructors behind them are where the traps live. All four build a ThreadPoolExecutor (or a subclass), and the two parameters that matter most are the queue type and the thread bound:

Executors.newFixedThreadPool(4);
// → ThreadPoolExecutor(4, 4, 0L, MILLISECONDS,
//        new LinkedBlockingQueue<>())   // UNBOUNDED queue

Executors.newCachedThreadPool();
// → ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, SECONDS,
//        new SynchronousQueue<>())     // NO queue, unbounded threads

Executors.newSingleThreadExecutor();
// → ThreadPoolExecutor(1, 1, 0L, MILLISECONDS,
//        new LinkedBlockingQueue<>())   // UNBOUNDED queue, one worker

Executors.newScheduledThreadPool(4);
// → ScheduledThreadPoolExecutor(4)        // delayed/periodic tasks

Two traps to memorize. Trap one: the cached pool has no queue and no thread limit — every task that arrives while all workers are busy spawns a brand-new thread. That was our 11,000-thread incident. Watch it happen with thirty 3-second tasks:

import java.util.concurrent.*;

public class PoolGrowth {
    public static void main(String[] args) throws Exception {
        Runnable sleeper = () -> {
            try { Thread.sleep(3000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        };
        ThreadPoolExecutor fixed = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
        ThreadPoolExecutor cached = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        for (int i = 0; i < 30; i++) { fixed.execute(sleeper); cached.execute(sleeper); }
        Thread.sleep(500); // let workers spin up
        System.out.println("fixed(4):  poolSize=" + fixed.getPoolSize() + " queued=" + fixed.getQueue().size());
        System.out.println("cached:    poolSize=" + cached.getPoolSize() + " queued=" + cached.getQueue().size());
        fixed.shutdownNow(); cached.shutdownNow();
    }
}
fixed(4):  poolSize=4 queued=26
cached:    poolSize=30 queued=0

Thirty blocked tasks, thirty OS threads — one per task, instantly. Scale that to a traffic spike against a slow downstream and you have the 2 a.m. graph. The cached pool is fine for short-lived tasks when you can prove the arrival rate is bounded; for anything that can block, it is a loaded gun.

Trap two: the fixed and single pools use an unbounded LinkedBlockingQueue. Workers stay fixed, which is good, but under sustained overload the queue grows without limit — every queued task holds its references, and you get an OutOfMemoryError instead of a fast, loud failure. A pool that can't say "no" will say it with an OOM. The fix is a bounded queue plus an explicit saturation policy — section 5 builds exactly that.

Principle: never accept a pool whose thread count and queue are both unbounded. One of the two must have a ceiling, or a traffic spike gets to pick your failure mode.

3. Sizing for CPU-bound work: more threads than cores buys nothing

When a task's bottleneck is the CPU — parsing, hashing, compression, model inference — a thread that isn't on a core is just waiting for one. So the sizing rule is a starting point, not a law: pool size ≈ number of cores. Past that, extra threads add context-switching overhead and split nothing, because the work can't go faster than the silicon.

Let's measure instead of trusting the rule. Each task burns a fixed amount of CPU (120 million Math.sqrt iterations); 8 tasks; pool sizes 1, 2, 4, 8, 16; median of 3 runs with the order shuffled each round (this VM's CPU allocation wobbles, so fixed-order runs would bias the comparison):

import java.util.*;
import java.util.concurrent.*;

public class CpuSizing {
    static final int ITERS = 120_000_000;

    static Callable<Double> burnTask() {
        return () -> {
            double s = 0.0;
            for (int i = 1; i <= ITERS; i++) s += Math.sqrt(i);
            return s;
        };
    }

    static long run(int poolSize, int tasks) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        List<Future<Double>> fs = new ArrayList<>();
        long t0 = System.nanoTime();
        for (int i = 0; i < tasks; i++) fs.add(pool.submit(burnTask()));
        for (Future<Double> f : fs) f.get();
        long ms = (System.nanoTime() - t0) / 1_000_000;
        pool.shutdown();
        pool.awaitTermination(30, TimeUnit.SECONDS);
        return ms;
    }

    public static void main(String[] args) throws Exception {
        System.out.println("availableProcessors = " + Runtime.getRuntime().availableProcessors());
        System.out.println("warmup result: " + burnTask().call()); // JIT warm-up
        // ... 3 reps, pool sizes shuffled per rep (bookkeeping omitted)
    }
}
availableProcessors = 2
warmup result: 8.763560974854962E11
--- medians ---
pool=1  runs=[5735, 9375, 11916] median=9375 ms
pool=2  runs=[5029, 5441, 6495] median=5441 ms
pool=4  runs=[4901, 5472, 5703] median=5472 ms
pool=8  runs=[4090, 4395, 5127] median=4395 ms
pool=16 runs=[4557, 5034, 6685] median=5034 ms

Three shuffled reps of 8 tasks × 120M iterations each; only the medians are shown above (the per-rep lines are omitted for space).

Read it honestly. This is a shared VM and the absolute numbers are noisy — look at the spread within each pool size. Two things are stable across every run I did: one thread is clearly the slowest (~9.4s median), and pools of 2, 4, 8, and 16 all land in the same ~4.4–5.5s band. The exact ordering among 2/4/8/16 is noise; the plateau is the signal. Going from 1 to 2 threads bought ~1.7×. Going from 2 to 16 bought nothing — there are only 2 cores, and sixteen threads can't compute on cores that don't exist.

CPU-bound: median wall time vs pool size (2-core VM) 0 2500 5000 7500 10000 ms 1 2 4 8 16 pool size (threads) 2-core plateau 9375 5441 5472 4395 5034 Medians of 3 shuffled runs; within-run spread was ±1–3s on this shared VM — the plateau, not the exact ordering, is the takeaway.

Rule of thumb (CPU-bound): start at poolSize = availableProcessors. Measure. Only deviate if measurement says so — e.g., one extra thread can occasionally cover GC pauses, but "16 threads on 2 cores for hashing" is never the answer.

4. Sizing for IO-bound work: waiting threads are cheap, waiting time is not

Now flip the bottleneck. A task that calls a database, a REST API, or a file system spends most of its life blocked — parked, consuming almost no CPU, just waiting for bytes. A blocked thread can't do another task's waiting for it, so throughput is roughly proportional to how many tasks can wait at once. The rule of thumb here: pool size ≈ cores × (1 + wait time / compute time) — a starting point to measure from, not a law. When wait dominates compute, that number gets large, and the real limit becomes memory per thread and downstream capacity, not cores.

Measure it. 200 tasks, each sleeping 50 ms (a stand-in for a 50 ms downstream call), pools of 2 through 32, median of 3 shuffled runs:

static Runnable ioTask() {
    return () -> {
        try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    };
}
// per pool size: submit 200 tasks, time until all Future.get() return
--- medians ---
pool=2  runs=[5022, 5022, 5050] median=5022 ms (40 tasks/s)
pool=4  runs=[2507, 2538, 2541] median=2538 ms (79 tasks/s)
pool=8  runs=[1256, 1257, 1270] median=1257 ms (159 tasks/s)
pool=16 runs=[651, 653, 654] median=653 ms (306 tasks/s)
pool=32 runs=[351, 355, 357] median=355 ms (563 tasks/s)

Three shuffled reps of 200 tasks × 50 ms sleep; medians shown, per-rep lines omitted.

Unlike the CPU experiment, this one is rock-stable — every rep landed within a few milliseconds of its median. And the pattern is the mirror image of section 3: doubling the pool (nearly) halves the wall time, all the way to 32 threads on a 2-core box. Throughput went 40 → 79 → 159 → 306 → 563 tasks/s. Sleeping threads don't compete for cores, so the core count is nearly irrelevant; what matters is how many 50 ms waits can overlap.

IO-bound: throughput vs pool size (200 × 50ms sleeps) 0 150 300 450 600/s 2 4 8 16 32 pool size (threads) 40/s 79/s 159/s 306/s 563/s Near-linear scaling: sleeping threads don't fight over 2 cores. The ceiling here is thread memory and downstream capacity, not CPU.

Two honest caveats before you size a production pool at 500 threads. First, each platform thread reserves stack memory (default 1 MB of virtual address space each) and costs the scheduler — 10,000 parked threads is a different machine than 32. Second, your downstream has a limit: 500 concurrent connections to a database with a 50-connection pool just moves the queueing somewhere else, with worse observability. Size the pool against the scarcest resource in the chain, and put a bounded queue in front (next section) so a slowdown degrades loudly instead of melting.

Rule of thumb (IO-bound): start at cores × (1 + wait/compute), measure throughput as you grow the pool, and stop when throughput stops climbing or the downstream complains. The number will be much bigger than core count — that's normal, not a bug.

5. When the pool is full: bounded queues and the four saturation policies

Here is the submission path inside ThreadPoolExecutor, and it's worth memorizing because everything about overload behavior falls out of it:

submit(task):
  if fewer than corePoolSize workers are running → start a new worker with this task
  else if the queue accepts the task           → queue it
  else if fewer than maximumPoolSize workers   → start a new worker with this task
  else                                         → saturation policy fires

For a fixed pool (core == max), step 3 never happens, so the policy fires exactly when all workers are busy and the queue is full. With the factory methods' unbounded queue, step 2 always succeeds and the policy never fires — which is why we build our own pool with a bounded queue:

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Saturation {
    static void runDemo(String name, RejectedExecutionHandler policy) throws InterruptedException {
        BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(2); // bounded!
        ThreadPoolExecutor pool = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS, queue, policy);
        AtomicInteger rejected = new AtomicInteger(), completed = new AtomicInteger();
        AtomicInteger ranOnSubmitter = new AtomicInteger();
        for (int i = 0; i < 10; i++) {
            try {
                pool.execute(() -> {
                    if (Thread.currentThread().getName().equals("main")) ranOnSubmitter.incrementAndGet();
                    try { Thread.sleep(300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                    completed.incrementAndGet();
                });
            } catch (RejectedExecutionException e) {
                rejected.incrementAndGet();
            }
        }
        pool.shutdown();
        pool.awaitTermination(15, TimeUnit.SECONDS);
        System.out.printf("%-18s rejected=%d completed=%d ranOnMainThread=%d%n",
                name, rejected.get(), completed.get(), ranOnSubmitter.get());
    }

    public static void main(String[] args) throws Exception {
        runDemo("AbortPolicy", new ThreadPoolExecutor.AbortPolicy());
        runDemo("CallerRunsPolicy", new ThreadPoolExecutor.CallerRunsPolicy());
        runDemo("DiscardPolicy", new ThreadPoolExecutor.DiscardPolicy());
        runDemo("DiscardOldestPolicy", new ThreadPoolExecutor.DiscardOldestPolicy());
    }
}

Two workers, a queue of two, ten 300 ms tasks — so at most 4 tasks fit and the other 6 must hit the policy. Real output:

AbortPolicy        rejected=6 completed=4 ranOnMainThread=0
CallerRunsPolicy   rejected=0 completed=10 ranOnMainThread=2
DiscardPolicy      rejected=0 completed=4 ranOnMainThread=0
DiscardOldestPolicy rejected=0 completed=4 ranOnMainThread=0

Read each line as a design decision:

AbortPolicy (the default) throws RejectedExecutionException to the submitter: 6 tasks refused, 4 completed. Loud and honest — but your code must catch it, or a burst becomes a 500-error storm. If you pick this (often the right default for request handling), handle the exception deliberately: retry with backoff, fail the request fast, shed load at the edge.

CallerRunsPolicy runs the overflow task on the submitting thread: 0 rejected, all 10 completed, 2 ran on main. This is a self-throttling feedback loop — while the pool is saturated, the submitter is busy running tasks instead of submitting more, so submissions naturally slow to the pool's drain rate. Elegant, but the latency spike lands on whatever thread submits (your request thread), so only use it when the submitter can afford to wait.

DiscardPolicy silently drops the new task: 0 rejected, only 4 completed — 6 tasks vanished without a trace. No exception, no log, no metric. This is almost never what you want; a silent drop is a data-loss bug wearing a reliability costume.

DiscardOldestPolicy drops the oldest queued task to make room: same numbers here, 6 tasks lost — just different victims. It has a legitimate niche (e.g., a metrics pipeline where only the latest value matters), but for request work it's DiscardPolicy with extra steps.

Principle: pick your saturation behavior on purpose, in code review, not at 2 a.m. For most services: bounded queue + AbortPolicy with a deliberate catch, or CallerRunsPolicy when the submitter may block. If you can't explain why you chose Discard, don't.

6. Graceful shutdown: the three lines that save your deploys

Pool worker threads are non-daemon by default: the JVM will not exit while they exist, even if they have nothing to do. That's our hanging-deploy incident — a pool that was never shut down kept the old JVM alive forever. The shutdown protocol is three steps, and each does exactly one thing:

shutdown() — stop accepting new tasks; finish the ones already queued. It does not interrupt running tasks.

awaitTermination(timeout) — block until all tasks finish, the timeout elapses, or the thread is interrupted. Returns true if the pool actually terminated.

shutdownNow() — interrupt the workers and return the tasks that never started. "Interrupt" is a request: tasks blocked in sleep, wait, or blocking-queue operations get an InterruptedException; pure compute loops must check Thread.currentThread().isInterrupted() themselves, or they will ignore you.

import java.util.List;
import java.util.concurrent.*;

public class ShutdownDemo {
    public static void main(String[] args) throws Exception {
        System.out.println("=== A: graceful shutdown of a finishing task ===");
        ExecutorService pool = Executors.newSingleThreadExecutor();
        pool.submit(() -> { try { Thread.sleep(800); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } });
        pool.shutdown();
        boolean ok = pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("awaitTermination(5s) -> " + ok + ", pool terminated = " + pool.isTerminated());

        System.out.println("=== B: shutdown() alone cannot stop a cooperative long task ===");
        ExecutorService pool2 = Executors.newSingleThreadExecutor();
        Future<?> f = pool2.submit(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                double x = 0; for (int i = 0; i < 1_000_000; i++) x += Math.sqrt(i);
            }
            System.out.println("task saw interrupt and exited its loop");
        });
        pool2.shutdown();
        boolean quick = pool2.awaitTermination(2, TimeUnit.SECONDS);
        System.out.println("shutdown(); awaitTermination(2s) -> " + quick + " (still running = " + !f.isDone() + ")");
        List<Runnable> pending = pool2.shutdownNow();
        System.out.println("shutdownNow() returned " + pending.size() + " never-started task(s)");
        boolean after = pool2.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("awaitTermination(5s) -> " + after + ", task done = " + f.isDone());
    }
}
=== A: graceful shutdown of a finishing task ===
awaitTermination(5s) -> true, pool terminated = true
=== B: shutdown() alone cannot stop a cooperative long task ===
shutdown(); awaitTermination(2s) -> false (still running = true)
task saw interrupt and exited its loop
shutdownNow() returned 0 never-started task(s)
awaitTermination(5s) -> true, task done = true

The sequence in part B is the whole lesson: shutdown() politely waits, but the task never finishes on its own, so awaitTermination(2s) returns false — your signal to escalate. shutdownNow() interrupts the worker, the task's isInterrupted() check sees it and exits, and the pool terminates. Two production notes: first, if your tasks swallow interrupts (empty catch (InterruptedException e) {}), shutdownNow() degrades to a suggestion — always either rethrow or re-set the flag with Thread.currentThread().interrupt(). Second, wire this into your app's lifecycle (a JVM shutdown hook, or your framework's destroy callback) — a pool created in a static initializer with no shutdown path is a deploy hang waiting for a Friday evening.

Principle: every pool you create needs an owner and a shutdown path. If you can't name both, don't create the pool.

7. Why raw Thread is almost never right

After six sections of pools, the question answers itself — but let's measure the actual failure mode, because it's not thread-creation cost. A burst of 4,000 tasks, each sleeping 100 ms: once through a fixed pool of 8, once as 4,000 raw Thread objects, tracking peak concurrent tasks:

fixed pool(8): wall=50141 ms peakConcurrentTasks=8
raw Thread  : wall=866 ms peakConcurrentTasks=1318

Look at what the raw version bought its speed with: a peak of 1,318 concurrent OS threads — each with its own stack reservation and scheduler entry — versus 8. On this small burst the machine survived; on a bigger burst, or with tasks that block longer, that number keeps climbing until the scheduler chokes or native memory runs out. And thread creation was never the bottleneck: 2,000 raw thread starts added only ~160 ms over the pooled version in a separate micro-test. The cost isn't starting threads. It's having no bound on how many exist at once.

A pool gives you four things raw threads don't: a bound on concurrency, a queue that turns bursts into orderly waiting, a saturation policy that decides what "too much" means, and a lifecycle you can shut down. Raw Thread still has legitimate uses — a handful of long-lived background threads with explicit names, or taking control of thread factories and priorities — but "one per request" and "one per task" belong to pools. (And in the next post, to something even better.)

8. The sizing cheat sheet

OLD-WORLD THREAD POOL CHEAT SHEET
==================================
CPU-bound (hashing, parsing, compression):
  pool ≈ Runtime.getRuntime().availableProcessors()
  More threads than cores: measured 0% gain (section 3).

IO-bound (DB, HTTP, filesystem waits):
  pool ≈ cores × (1 + waitTime / computeTime) … then MEASURE.
  Observed: 40 → 563 tasks/s growing pool 2 → 32 on 2 cores (section 4).
  Real ceilings: thread stack memory, downstream connection limits.

Always:
  - Bound the queue (ArrayBlockingQueue), or overload = OOM.
  - Choose a saturation policy deliberately (Abort / CallerRuns / Discard / DiscardOldest).
  - shutdown() → awaitTermination(timeout) → shutdownNow() on the way out.
  - Never cached-pool + blocking tasks. Never unbounded + unbounded.

Interview one-liners:
  "Why not one thread per request?"  → No bound on concurrency; bursts
     create thousands of OS threads (measured peak: 1318 vs 8).
  "Fixed vs cached pool?"            → Fixed bounds threads, queues the rest;
     cached bounds nothing — it spawns a thread per concurrent task.
  "shutdown vs shutdownNow?"         → shutdown() drains gracefully;
     shutdownNow() interrupts workers and returns unstarted tasks.

What's next

You now own the old world: pools decouple tasks from threads, sizing follows the bottleneck (cores for CPU, wait-time for IO), overload needs a deliberate policy, and every pool needs a shutdown path. The whole post in one mental model:

task arrives
  → workers < core?            start a worker
  → else queue has room?       queue it (BOUND the queue)
  → else workers < max?        start a worker
  → else                       saturation policy (choose deliberately)
pool retires
  → shutdown() → awaitTermination(t) → shutdownNow() (tasks must honor interrupts)

Three lines to carry forward: size by the bottleneck, not by vibes — cores for CPU, wait-time for IO, measured both ways. A pool that can't say "no" will say it with an OOM. Every pool needs an owner and a shutdown path.

The next post in this track, Virtual Threads: One Per Task, breaks the tradeoff this whole post was built on. Platform threads are expensive OS resources, so we ration them with pools — but what if a thread cost almost nothing to create and blocked almost for free? Then "one thread per task" stops being reckless and starts being the simplest correct design. We'll measure virtual threads against everything you just learned, and find out which sizing rules survive.

Field check before you move on: (1) Run the CPU experiment on your own machine with the CpuSizing program — find the pool size where your wall time stops improving and confirm it matches your core count (nproc / availableProcessors()). (2) In the IO experiment, change the sleep from 50 ms to 200 ms and predict the pool-32 wall time before you run it — then check. (3) Rebuild the saturation demo with pool=1, queue=1, 6 tasks, and each of the four policies: write down rejected/completed for each before running, then verify. (4) Find one ExecutorService in a codebase you work on and answer: is its queue bounded, what is its saturation policy, and who calls shutdown()? If you can't answer all three, you've found your first production fix. Bring the answers to the next post — virtual threads change the sizing math, but not the discipline.

Continue: Java Learning Roadmap 2026

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions