Design Pattern

Thread Pool Pattern

Clean Java-only production-ready implementation.


What Problem It Solves

A thread pool keeps a small, fixed group of worker threads alive and feeds them tasks from a queue, so the cost of a thread is paid once instead of once per task. It also gives the system a single place to say how much work may run at the same time and what happens when more arrives.

Why a Thread Per Task Fails

Starting a new thread for every request looks simple and works in a demo. Under real load it fails in three separate ways.

FailureWhat happensWhat the pool changes
Creation costCreating and tearing down an OS thread costs tens of microseconds or more plus kernel scheduling work. For a task that runs for a millisecond, that overhead is a large share of the totalWorkers are created once and reused for thousands of tasks
Unbounded threadsA spike of 10,000 requests becomes 10,000 runnable threads. The scheduler spends its time context switching, so throughput falls exactly when load risesConcurrency is capped at the worker count and the excess waits in a queue
MemoryEach Java thread reserves a stack, typically 1 MB by default on 64-bit Linux. 10,000 threads reserve about 10 GB of address space and the JVM can fail with an out of memory error while creating a native threadMemory for stacks is fixed up front and the queue has an explicit size

What a Pool Gives You

A pool turns a free-for-all into a controlled pipeline. Concurrency is bounded, threads are reused, overload becomes a visible event through the queue and the rejection policy, shutdown has a defined meaning, and callers get a future they can wait on for the result.

How a Thread Pool Works

The design has three parts: a bounded set of workers, a task queue between callers and workers, and a small API made of submit and shutdown. Callers never touch a worker. They hand a task to the pool and the pool decides when and where it runs.

The Moving Parts

Loading...

Each worker runs one loop. It takes a task from the queue, blocking if the queue is empty, runs the task inside a try and catch, and then goes back for the next one. submit wraps the task in a future so the result or the exception can travel back to the caller.

A Worked Trace

Take a pool with 2 workers and a queue of capacity 2 that uses the abort policy. Six tasks arrive while every task runs for a long time. The Java program in the first tab and the standard library program in the last tab both reproduce this trace.

StepEventRunningQueueOutcome
1submit t1t1emptyA free worker starts it at once
2submit t2t1, t2emptyThe second worker starts it
3submit t3t1, t2t3Both workers busy, so t3 waits
4submit t4t1, t2t3, t4Queue is now full
5submit t5 and t6t1, t2t3, t4Rejected: 4 accepted, 2 rejected
6t1 finishest2, t3t4The freed worker takes t3 from the head
7submit t7t2, t3t4, t7Room exists again, so it is accepted

Notice that the pool never ran more than two tasks at once and never held more than two waiting. The pool size and the queue capacity together are the hard limit on how much work the process can have in flight, which is the property a thread per task design lacks.

Choosing the Pool Size

The right worker count depends on what a task spends its time doing. A task that computes the whole time can keep one core fully busy, while a task that mostly waits leaves its core free for others.

CPU Bound Work

When tasks only compute, extra threads cannot add throughput because every core is already saturated. A pool of about as many workers as cores is right, and some teams add one spare to cover a brief stall. More threads than that only adds context switching.

I/O Bound Work

When tasks wait on a database, a network call or a disk, a thread sits idle for most of its life, so you need more threads than cores. A standard starting formula is threads = cores x (1 + wait / compute).

A Worked Number

Take a machine with 8 cores and a task that computes for 20 ms and then waits 80 ms on a database. The formula gives 8 x (1 + 80 / 20) = 40 threads. Check it from the other side. Each task holds a thread for 100 ms, so 40 threads finish 40 / 0.1 s = 400 tasks per second. Those 400 tasks need 400 x 20 ms = 8 core seconds of compute every second, which is exactly the 8 cores available. Fewer threads would leave cores idle and more would only queue work inside the CPU.

WorkloadComputeWaitPool size on 8 coresThroughput ceiling
Pure CPU20 ms0 ms8 x (1 + 0) = 88 / 0.02 s = 400 tasks per second
Database call20 ms80 ms8 x (1 + 4) = 4040 / 0.1 s = 400 tasks per second
Slow remote API5 ms95 ms8 x (1 + 19) = 160160 / 0.1 s = 1,600 tasks per second

Limits the Formula Ignores

The formula assumes the thing you wait on can serve every thread. If the database allows only 20 connections, a pool of 40 workers just moves the queue into the connection pool, so cap the worker count at the smallest downstream limit. Measure the real wait to compute ratio under load, because it changes as dependencies slow down. Keep slow and fast workloads in separate pools so one stalled dependency cannot take every worker, which is the bulkhead idea in Circuit Breaker, Retries and Bulkheads.

Queues and Rejection Policies

The queue absorbs bursts and the rejection policy decides what happens when the queue is full. Together they are the pool's overload story, so they deserve as much thought as the worker count.

Choosing the Queue

QueueBehaviourUse it when
Unbounded LinkedBlockingQueueNever rejects. A backlog grows in memory and latency rises with no errorAlmost never in production
Bounded ArrayBlockingQueueRejects when full, so overload is visible to the callerThe default choice, sized from throughput and acceptable wait
SynchronousQueueHolds nothing and hands each task straight to a free worker, otherwise the pool starts another threadYou want no buffering and have capped the maximum thread count
PriorityBlockingQueueOrders tasks by priority but is unbounded and can starve low priority workPriority matters and you add your own admission limit

To size a bounded queue, decide how long a task may wait and multiply by throughput. At 400 tasks per second and a quarter second of tolerable wait, a queue of about 100 slots is enough, and anything beyond that only adds latency users would not accept anyway.

Why an Unbounded Queue Hides Overload

Suppose 500 tasks per second arrive and the pool completes 400. The backlog grows by 100 tasks every second. After a minute 6,000 tasks are waiting and each new one waits 6,000 / 400 = 15 seconds, yet no call has failed, so dashboards that count errors stay green. The process finally dies from memory or from timeouts far downstream. A bounded queue turns the same situation into rejections within the first second, which is the signal an autoscaler or a caller can act on.

There is a second cost in Java. ThreadPoolExecutor starts threads above the core size only when the queue is full. With an unbounded queue it never is, so a pool configured with core 4, maximum 8 and an unbounded queue never runs more than 4 workers. The last tab prints exactly this, with a pool size of 4 and 16 queued tasks, and it is the configuration used in the Job Scheduler blueprint.

Rejection Policies

PolicyWhat happens to the overflow taskRiskFits
AbortThe submit call throws RejectedExecutionExceptionCallers must handle the exception or it surfaces as a crashRequest handlers that can answer 429 or 503
Caller runsThe submitting thread runs the task itselfA long task blocks the producer and ordering is lostInternal pipelines where slowing the producer is the goal
DiscardThe new task is dropped silentlyLost work, and a pending future if nobody cancels itBest effort work such as metrics or debug logs
Discard oldestThe task at the head of the queue is dropped and the new one is queuedDrops the task that waited longest, which may be the most importantLatest value wins data such as sensor readings or price ticks

Caller runs is the only policy that creates backpressure without losing anything, because a busy producer cannot submit more work. In a single threaded runtime such as Node it does not work that way, which is why the TypeScript tab leaves it out. The Logger Library uses the discard idea with a bounded queue of 1000 records and prints a warning when a record is dropped. For the wider picture of shedding load on purpose, read Backpressure and Load Shedding.

Shutdown: Graceful Versus Immediate

A pool owns threads, so it has to be told when to stop. There are two honest answers to that question and they trade completeness against speed.

QuestionGraceful: shutdown()Immediate: shutdownNow()
Accepts new tasksNo, later submits are rejectedNo, later submits are rejected
Tasks waiting in the queueAll of them still runRemoved and handed back to the caller, never started
Tasks already runningRun to completionJava interrupts them, Python and JavaScript cannot interrupt them so they finish
Use it whenThe process is stopping normally and no work may be lostA deadline has passed or the process is being killed

The Standard Recipe

Call the graceful shutdown first, wait for termination with a timeout, and only if the wait times out switch to the immediate one and wait a little longer. The hand-built programs print both outcomes side by side. With 1 busy worker and 3 queued tasks, graceful shutdown runs all 3 and hands back none, while immediate shutdown runs 0 and hands back 3. Both reject a submit that arrives after the call.

Two details cause most bugs. Workers are usually non-daemon threads, so forgetting to shut a pool down keeps the process alive after main returns. And interruption is cooperative, so shutdownNow() only stops a task that is blocked in a call that reacts to it, such as sleep or await. A tight compute loop ignores it unless the loop checks the interrupt flag.

The Java and Python pools also close a small race. The check that the pool is still accepting and the insert into the queue happen under one lock, so a task cannot slip in just after the last worker has decided to exit. The TypeScript pool does not need the lock because only one piece of code runs at a time.

Exceptions in Workers and Futures for Results

Two questions arrive together in every review of a pool. What happens to the worker when a task throws, and how does the caller get the answer back.

A Worker Must Survive a Failing Task

If an exception escapes the worker loop, that thread ends and the pool silently loses capacity. Each hand-built pool therefore isolates the task. The Java loop wraps task.run() in a catch for Throwable and counts the failure. The Python loop catches BaseException inside _run and stores it on the future. The TypeScript wrapper catches inside run and rejects only that task's promise, after which the slot is freed and the next queued task starts. Each driver proves it by failing a task and then showing that the same workers still serve the next one.

The standard library behaves differently depending on how the task was submitted. A task sent through execute that throws kills its worker thread and the pool starts a replacement, which the last tab shows when job-0 is replaced by job-1. A task sent through submit never kills the worker because the exception is stored in the future. The cost is that nobody sees the failure unless somebody calls get.

Futures Carry the Result Back

A future is a handle to a value that does not exist yet. In Java get() blocks until the task finishes and throws ExecutionException with the original error as its cause. In Python result() re-raises the original exception and in TypeScript the promise rejects. Waiting without a limit is risky, so use get(timeout) or result(timeout). A task that the pool drops must still complete its future, which is why the discard policies in the Java and Python pools cancel it and why the TypeScript pool rejects its promise. Otherwise a caller waiting on that future waits forever.

Common Interview Traps

TrapWhyFix
Executors.newFixedThreadPool for a service that can be overloadedIts queue is unbounded, so overload becomes a growing backlog and a late out of memory error, with no rejection to warn anyoneBuild a ThreadPoolExecutor with a bounded ArrayBlockingQueue and an explicit rejection policy
Executors.newCachedThreadPool under a traffic spikeIts maximum thread count is effectively unlimited, so a spike creates thousands of threads, which is thread per task againCap the maximum pool size and use a bounded queue
Core 4, maximum 8, unbounded queueThreads above core start only when the queue is full. With an unbounded queue the maximum is never reachedBound the queue so the maximum can matter, or set core equal to maximum on purpose
One pool size for CPU work and I/O workCPU tasks want about the core count and waiting tasks want several times that. One number wastes one of themSize each workload with cores x (1 + wait / compute) and give slow dependencies their own pool
A task throws and the worker thread diesCapacity shrinks one failure at a time until nothing is left to run tasksCatch around task.run() in a hand-built pool and install an uncaught exception handler on the threads of a library pool
Exception swallowed inside a futuresubmit stores the failure in the future, so if nobody calls get the error is never seenAlways read the future, or log inside a wrapper around the task
A task blocks on another task from the same bounded poolEvery worker can end up waiting for work that is stuck in the queue behind them, which is a thread starvation deadlockRun dependent work on a separate pool or compose futures without blocking
Dropping a task but leaving its future pendingA caller blocked on get waits forever for a task that will never runCancel or fail the future of every task a policy or shutdown drops
Forgetting to shut the pool downNon-daemon workers keep the process alive, and a forced kill loses queued workGraceful shutdown, a timed wait, then immediate shutdown
queue.Queue() with no maxsize in PythonA maximum size of 0 means unbounded, so overload hides in memory againAlways pass a positive maxsize and handle queue.Full
Expecting a JavaScript pool to give parallelismOne thread runs all your code, so a worker limit only caps in-flight promises. A CPU heavy task still blocks the event loopUse worker threads or processes for CPU work and keep the limiter for I/O
Thread local state left behindWorkers are reused, so the next task can see a user or request id set by the previous oneClear thread locals in a finally block at the end of every task

When to Use It and When Not To

Reach for a thread pool when many short, independent tasks arrive and you must cap how many run at once. Typical cases are handling requests, sending notifications, processing uploads and running scheduled jobs. A pool is a poor fit when the shape of the work is different, and the table below says what to use instead.

SituationBetter fitWhy
A few long-lived activities such as a background pollerA dedicated threadIt never needs reuse and would hold a pool worker for its whole life
Many concurrent network calls in Node or Python asyncioThe event loop with a concurrency limiterWaiting costs no thread, which is what the TypeScript tab models
CPU parallelism in PythonProcessesThe global interpreter lock stops threads running Python code in parallel
Java 21 or later with huge numbers of blocking tasksVirtual threads plus a Semaphore for the scarce resourceThreads are cheap, so you limit the downstream resource instead of the thread count
Objects that are borrowed and returned, such as connectionsAn object poolThe thing being reused is a resource, not a worker

The last row is the link to a sibling idea. A thread pool is close to the Object Pool Pattern with one twist. Instead of lending a worker to a caller, the pool keeps the worker and pushes tasks to it through a queue.

Where It Shows Up in LLD Problems

These problems really build or configure a worker pool. Each line says what to look for in the Java blueprint so you can compare it with the ideas above.

  • Job Scheduler hands every due job to a ThreadPoolExecutor through workerPool.submit. Its executeJob catches a failing job, notifies observers and requeues it for a retry, so a bad job never takes a worker down. Its pool uses core 4, maximum 8 and an unbounded queue, so it never runs more than 4 workers.
  • Online Judge (LeetCode-lite) runs each submission through Executors.newFixedThreadPool(4) so a slow code runner never blocks the caller of submit. Its Python blueprint starts one thread per submission, which is the thread per task shape this page warns about.
  • Notification Service starts 2 workers from a fixed pool and each runs a processQueue loop that polls a PriorityBlockingQueue with a timeout, so a stop flag is noticed quickly.
  • Thumbnail Service starts threadCount workers from a fixed pool that all loop on one blocking queue of job ids. Its shutdown uses the immediate form on the worker pool and on the retry scheduler.
  • Logger Library is the single worker case. One thread from newSingleThreadExecutor drains a bounded queue of 1000 records, a full queue drops the record with a warning, and shutdown lets the worker drain what is left.
  • Workflow Engine runs independent steps in parallel on a fixed pool of 4 in Java and on ThreadPoolExecutor(max_workers=4) in Python.

Implementation

Four Runnable Programs

The first three tabs are hand-built pools that share one design: a fixed set of workers, a bounded queue, a rejection policy, a graceful and an immediate shutdown, and a worker loop that survives a failing task. Each ends in a driver that prints proof of the behaviour. The fourth tab shows the same ideas with the standard library ThreadPoolExecutor.

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

enum RejectPolicy { ABORT, CALLER_RUNS, DISCARD, DISCARD_OLDEST }

// A minimal fixed-size pool: N workers, one bounded queue, one rejection policy.
class SimpleThreadPool {
    private final BlockingQueue<Runnable> queue;
    private final List<Thread> workers = new ArrayList<>();
    private final RejectPolicy policy;
    private final Object gate = new Object();   // makes "accepting?" and "offer" one atomic step
    private final AtomicInteger failedTasks = new AtomicInteger();
    private volatile boolean accepting = true;
    private volatile boolean stopNow = false;

    SimpleThreadPool(int workerCount, int queueCapacity, RejectPolicy policy) {
        this.queue = new ArrayBlockingQueue<>(queueCapacity);
        this.policy = policy;
        for (int i = 0; i < workerCount; i++) {
            Thread worker = new Thread(this::workerLoop, "worker-" + i);
            workers.add(worker);
            worker.start();
        }
    }

    <T> Future<T> submit(Callable<T> task) {
        FutureTask<T> future = new FutureTask<>(task);   // captures the result or the exception
        execute(future);
        return future;
    }

    void execute(Runnable task) {
        boolean runHere = false;
        synchronized (gate) {
            if (!accepting) throw new RejectedExecutionException("pool is shut down");
            if (!queue.offer(task)) {                    // queue full: apply the policy
                switch (policy) {
                    case ABORT -> throw new RejectedExecutionException("queue is full");
                    case CALLER_RUNS -> runHere = true;
                    case DISCARD -> cancel(task);
                    case DISCARD_OLDEST -> {
                        cancel(queue.poll());
                        queue.offer(task);
                    }
                }
            }
        }
        if (runHere) task.run();                         // run on the caller thread, outside the lock
    }

    // A dropped task must finish its future, otherwise a caller blocked on get() waits forever.
    private static void cancel(Runnable dropped) {
        if (dropped instanceof Future<?> future) future.cancel(false);
    }

    private void workerLoop() {
        while (!stopNow) {
            Runnable task;
            try {
                task = queue.poll(50, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                continue;                                // loop condition re-checks stopNow
            }
            if (task == null) {
                if (!accepting && queue.isEmpty()) return;   // drained after a graceful shutdown
                continue;
            }
            try {
                task.run();
            } catch (Throwable t) {
                failedTasks.incrementAndGet();           // the worker survives and takes the next task
            }
        }
    }

    void shutdown() {                                    // graceful: finish everything already queued
        synchronized (gate) { accepting = false; }
    }

    List<Runnable> shutdownNow() {                       // immediate: hand back tasks that never started
        List<Runnable> neverStarted = new ArrayList<>();
        synchronized (gate) {
            accepting = false;
            stopNow = true;
            queue.drainTo(neverStarted);
        }
        for (Thread worker : workers) worker.interrupt();
        return neverStarted;
    }

    boolean awaitTermination(long millis) throws InterruptedException {
        long deadline = System.currentTimeMillis() + millis;
        for (Thread worker : workers) worker.join(Math.max(1, deadline - System.currentTimeMillis()));
        return aliveWorkers() == 0;
    }

    int aliveWorkers() { return (int) workers.stream().filter(Thread::isAlive).count(); }
    int failedTasks() { return failedTasks.get(); }
}

public class Main {
    public static void main(String[] args) throws Exception {
        sizeAndFailureDemo();
        for (RejectPolicy policy : RejectPolicy.values()) System.out.println(policyDemo(policy));
        shutdownDemo(false);
        shutdownDemo(true);
    }

    // 100 tasks on 4 workers, then a task that throws, then proof the workers are all still alive.
    static void sizeAndFailureDemo() throws Exception {
        SimpleThreadPool pool = new SimpleThreadPool(4, 100, RejectPolicy.ABORT);
        Set<String> threadsUsed = ConcurrentHashMap.newKeySet();
        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            int n = i;
            futures.add(pool.submit(() -> {
                threadsUsed.add(Thread.currentThread().getName());
                return n * n;
            }));
        }
        long sum = 0;
        for (Future<Integer> f : futures) sum += f.get();
        System.out.println("1) 100 tasks, sum of squares = " + sum + ", threads used <= 4: " + (threadsUsed.size() <= 4));

        Future<Integer> bad = pool.submit(() -> { throw new IllegalStateException("boom"); });
        try {
            bad.get();
        } catch (ExecutionException e) {
            System.out.println("2) failure surfaced through the future: " + e.getCause());
        }
        pool.execute(() -> { throw new RuntimeException("raw runnable fails"); });
        while (pool.failedTasks() < 1) Thread.sleep(5);
        System.out.println("   workers alive after both failures: " + pool.aliveWorkers()
                + ", next task returns: " + pool.submit(() -> "still serving").get());
        pool.shutdown();
        pool.awaitTermination(2000);
    }

    // One busy worker, a queue of 2, then a third overflow task. What happens depends on the policy.
    static String policyDemo(RejectPolicy policy) throws Exception {
        SimpleThreadPool pool = new SimpleThreadPool(1, 2, policy);
        CountDownLatch started = new CountDownLatch(1);
        CountDownLatch release = new CountDownLatch(1);
        List<String> ran = new CopyOnWriteArrayList<>();
        pool.execute(() -> {
            started.countDown();
            try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        started.await();
        Map<String, Future<String>> futures = new LinkedHashMap<>();
        String outcome = "all accepted";
        for (String name : new String[] {"t1", "t2", "t3"}) {
            try {
                futures.put(name, pool.submit(() -> {
                    ran.add(name + "@" + Thread.currentThread().getName());
                    return name;
                }));
            } catch (RejectedExecutionException e) {
                outcome = name + " rejected";
            }
        }
        release.countDown();
        pool.shutdown();
        pool.awaitTermination(2000);
        List<String> cancelled = new ArrayList<>();
        futures.forEach((name, f) -> { if (f.isCancelled()) cancelled.add(name); });
        return "3) " + policy + ": " + outcome + ", ran " + ran + ", cancelled " + cancelled;
    }

    static void shutdownDemo(boolean immediate) throws Exception {
        SimpleThreadPool pool = new SimpleThreadPool(1, 10, RejectPolicy.ABORT);
        CountDownLatch started = new CountDownLatch(1);
        CountDownLatch release = new CountDownLatch(1);
        AtomicInteger done = new AtomicInteger();
        pool.execute(() -> {
            started.countDown();
            try { release.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
        });
        started.await();
        for (int i = 0; i < 3; i++) pool.execute(done::incrementAndGet);
        int dropped = 0;
        if (immediate) dropped = pool.shutdownNow().size(); else pool.shutdown();
        boolean lateRejected = false;
        try {
            pool.execute(done::incrementAndGet);
        } catch (RejectedExecutionException e) {
            lateRejected = true;
        }
        release.countDown();
        pool.awaitTermination(2000);
        System.out.println("4) " + (immediate ? "shutdownNow" : "shutdown   ") + ": queued tasks that ran = "
                + done.get() + ", handed back = " + dropped + ", late submit rejected = " + lateRejected);
    }
}

๐Ÿ’ฌReview

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...