A thread pool runs many short tasks on a small, fixed set of reusable worker threads. Callers hand tasks to an executor, which puts them in a task queue; idle workers take them off and run them, one at a time each. Creating threads once instead of per task saves the creation cost, and the pool size caps how many threads can exist, so a burst of work queues up instead of exhausting memory. Nearly every server, job runner and async runtime is built on one.
Think of it like
A restaurant kitchen with a ticket rail
A restaurant does not hire a new cook for every order. It keeps a few cooks (the workers) and a rail of order tickets (the task queue). A free cook takes the next ticket, cooks it, and comes back for another. The rail has limited room: when it is full, the waiter stops taking orders for a moment and helps plate a dish himself (the caller runs the task). At closing time the manager announces it to every cook, not just one; the cooks finish the tickets on the rail and go home.
The problem
A server receives work in small pieces: requests, messages, files to resize. The simplest way to run each piece concurrently is to start a thread for it. In the visualizer above, the Before version does exactly that: a submitter thread S calls execute(t1) to execute(t4), and each call creates and starts a new thread (T1 to T4) that runs one task and exits.
class ThreadPerTaskExecutor implements Executor {
public void execute(Runnable task) {
Thread t = new Thread(task); // a new thread, a new stack
t.start(); // the OS schedules it
}
}It works, and for a handful of tasks it is fine. It hurts in three ways as load grows:
- Creation cost on every task. A platform thread is an operating-system thread: creating one means a system call, a kernel data structure and a stack (by default 1 MB of reserved address space for a Java thread on 64-bit Linux). For short tasks this setup can cost more than the work itself. In the visualizer it is the two steps
newandstarton S's lane for every task. - No upper bound. One thread per task means a burst of 1,000 tasks starts 1,000 threads. Under the Burst schedule, S starts T1, T2 and T3 before any of them has run, and the invariant At most 2 extra threads breaks at step 6; by step 8 four task threads are alive at once. Real bursts end in
OutOfMemoryError: unable to create native threador a machine that spends its time switching between threads. - No control. There is no single place to limit concurrency, measure a backlog, reject work under overload or shut everything down cleanly.
The pattern
Intent: decouple submitting a task from running it, and run tasks on a bounded set of long-lived worker threads that take them from a shared queue. A thread pool is Producer-Consumer with tasks as the items: submitters produce, workers consume. It is also an Object Pool whose pooled objects are threads.
- Worker
- A long-lived thread that loops: take a task from the queue, run it, repeat. When the queue is empty it sleeps on a condition instead of spinning.
- Task queue
- The buffer between submitters and workers. Bounded (a fixed capacity, as in the visualizer) or unbounded (risky: it grows without limit when workers fall behind).
- Executor
- The interface callers see:
execute(task)orsubmit(task)returning a future. It hides whether a task runs on a pool, a new thread or the caller. - Core and max size
- In Java's
ThreadPoolExecutor, the pool keeps up to core threads, adds threads up to max only when the queue is full, and lets the extra ones die after a keep-alive time without work. - Rejection policy
- What
executedoes when the queue is full and no more threads may be added: throw (AbortPolicy, Java's default), run the task in the caller (CallerRunsPolicy), drop it (DiscardPolicy) or drop the oldest queued task (DiscardOldestPolicy). - shutdown vs shutdownNow
shutdown()stops accepting tasks but lets queued and running ones finish.shutdownNow()also interrupts running tasks and returns the queued ones unrun. Either way, callawaitTerminationto wait for the workers to exit.
In the Thread pool version, S creates two workers, W1 and W2, once. execute locks the pool's lock, offers the task to a queue of capacity 2 and signals notEmpty; when the queue is full, the caller runs the task itself. A worker locks, waits in a while loop while the queue is empty and the pool is open, polls a task, unlocks, and runs the task outside the lock. shutdown() sets a flag and calls signalAll(); a worker that finds the queue empty after shutdown gets null from poll() and returns.
void work() {
while (true) {
Runnable r;
lock.lock();
try {
while (q.isEmpty() && !shutdown) notEmpty.await();
r = q.poll(); // null only after shutdown
} finally {
lock.unlock();
}
if (r == null) return; // the worker exits
r.run(); // outside the lock
}
}
void shutdown() {
lock.lock();
try {
shutdown = true;
notEmpty.signalAll(); // every idle worker must wake
} finally {
lock.unlock();
}
}Walkthrough
Pick Thread pool and the Idle at shutdown schedule, then step through. This run touches every part of the pattern in 49 steps.
- 1
Steps 1 to 4: create the workers once
S runs
new Threadandstartfor W1 and W2. These are the only two threads the pool will ever create; untilstart, a worker's lane is empty and its status reads not started. - 2
Steps 5 to 10: two tasks fit in the queue
execute(t1)andexecute(t2)each take three steps: lock, offer, unlock. Both offers succeed and the queue is full (2 of 2). Each offer signalsnotEmpty, but no worker is waiting yet, so the signals do nothing. - 3
Steps 11 to 20: the queue is full, the caller runs
execute(t3)finds the queue full: the offer fails, and the caller-runs policy makes S runt3itself. The same happens fort4. While S is busy running tasks it submits nothing else: a full queue slows the producer down instead of dropping work. - 4
Steps 21 to 33: one worker drains the queue
W1 starts late, takes
t1, runs it outside the lock, takest2, runs it, and then finds the queue empty with the pool still open, so it waits onnotEmptyand sleeps. - 5
Steps 34 to 36: the other worker has nothing to do
W2 locks, finds the queue empty and sleeps too. Both workers are now idle, which costs no CPU: the stat idle worker steps counts the steps they spend asleep.
- 6
Steps 37 to 39: shutdown wakes everyone
S locks, sets
shutdown = trueand callssignalAll(), which wakes both W1 and W2 (step 38). Each must re-acquire the lock before itsawait()returns. - 7
Steps 40 to 49: workers exit, S joins them
Each worker re-checks the loop condition: the queue is empty and
shutdownis set, so it stops waiting, pollsnull, unlocks and returns. S'sjoincalls return and the run ends with every task run once and every thread finished.
Now switch to Shutdown bug with the same schedule. Everything is identical until step 38, where signal() wakes only W1, the longest waiter. W1 exits; W2 keeps sleeping on notEmpty, and nobody will ever signal it again. At step 45, S calls join(W2) and the run ends in a deadlock: S waits for W2, W2 waits for a signal. In a real JVM the program simply never exits.
Before and after
Thread per task (Before)
- Burst: 4 threads created for 4 tasks, and 4 alive at once
- The bound At most 2 extra threads breaks at step 6
- Even under Idle at shutdown, where only one task thread is alive at a time, it still creates 4 threads
- Every thread is used for exactly one task and then thrown away
Thread pool (After)
- 2 threads created under every schedule, never more than 2 alive besides S
- Burst: the queue fills (max queue 2) and S runs
t3andt4itself, so nothing is dropped - Round robin: the workers keep pace, the queue never overflows, and each worker runs two tasks
- Shutdown completes in every interleaving: all workers exit
| Schedule | Version | Created | Most alive | Caller ran | Idle steps | Outcome |
|---|---|---|---|---|---|---|
| Burst | Before | 4 | 4 | n/a | n/a | bound broken, step 6 |
| Burst | Pool | 2 | 2 | t3, t4 | 0 | done, 43 steps |
| Idle at shutdown | Before | 4 | 1 | n/a | n/a | done, 20 steps |
| Idle at shutdown | Pool | 2 | 2 | t3, t4 | 7 | done, 49 steps |
| Idle at shutdown | Shutdown bug | 2 | 2 | t3, t4 | 15 | deadlock, step 45 |
| Round robin | Pool | 2 | 2 | none | 0 | done, 53 steps |
Variations
| Kind | How it works | Good for | Watch out for |
|---|---|---|---|
Fixed (newFixedThreadPool(n)) | n threads, kept forever, one shared queue | Steady CPU-bound or mixed work | The factory method uses an unbounded queue |
Cached (newCachedThreadPool()) | No queue (a SynchronousQueue): reuses an idle thread or creates a new one; idle threads die after 60 s | Many short, bursty tasks | No upper bound on threads: a burst behaves like thread per task |
Work stealing (ForkJoinPool) | Each worker has its own deque; idle workers steal from the others' tails | Recursive divide and conquer, parallel streams | Blocking calls inside tasks starve the pool |
Scheduled (ScheduledThreadPoolExecutor) | A delay queue ordered by run time | Timers, retries, periodic jobs | A slow periodic task delays the next run of itself |
| Virtual threads (Java 21) | newVirtualThreadPerTaskExecutor(): a cheap new virtual thread per task, carried by a small ForkJoinPool of platform threads | Many tasks that mostly block on I/O | Do not pool them; limit concurrency with a semaphore instead |
Core, max and the queue interact. Java's ThreadPoolExecutor.execute first starts a new thread if fewer than core threads exist, then tries the queue, and only when the queue refuses the task adds a thread up to max, and rejects after that. So with an unbounded queue, max is never reached; with a SynchronousQueue (no capacity) every task needs a free thread or a new one.
Virtual threads change the math for blocking I/O
Pools exist because platform threads are expensive. Java 21's virtual threads (JEP 444) are cheap enough to create one per task, even millions: when one blocks on I/O, the JVM unmounts it and its carrier thread runs another. For I/O-bound work this removes the reason to pool threads at all, and JEP 444 explicitly advises against pooling virtual threads. What a pool also gave you, a limit on concurrency (say, at most 20 calls to one database), you now get from a Semaphore. CPU-bound work still wants about one thread per core, and the carriers are themselves a pool of that size.
Sizing the pool
Too few threads leave cores idle while tasks wait; too many add memory, context switches and contention for little gain. Brian Goetz's Java Concurrency in Practice (section 8.2) gives the starting points:
N_cpu is the number of cores, U_cpu the target CPU utilization (0 to 1) and W/C the ratio of time a task spends waiting to time it spends computing.CPU-bound, 8 cores
9 threads
8 + 1, the extra one covers a thread stalled on a page fault
I/O-bound, 8 cores, W/C = 9
80 threads
8 × 1 × (1 + 9): each task waits 90 ms per 10 ms of CPU
Mixed work
Split it
Separate pools for CPU work and blocking calls, sized separately
Treat the formula as a first guess and then measure: the wait ratio changes with load, and the real limit is often a downstream resource. A pool of 200 threads in front of a database that allows 20 connections just moves the queue into the connection pool. Size the queue too: it should absorb normal bursts, and when it is full the rejection policy decides between slowing callers down (caller runs, blocking) and failing fast (abort), which is where Backpressure & Load Shedding starts.
In real code
- Java:
java.util.concurrent.ThreadPoolExecutorwith the factory methods inExecutors.ForkJoinPool.commonPool()runs parallel streams andCompletableFuture's async methods by default. Spring'sThreadPoolTaskExecutorand Tomcat's request threads (maxThreads, default 200) wrap the same idea. - Python:
concurrent.futures.ThreadPoolExecutor. Since Python 3.8 its defaultmax_workersismin(32, os.cpu_count() + 4), and its work queue is unbounded. Because of the GIL, threads in standard CPython help with I/O-bound work; CPU-bound work goes toProcessPoolExecutor. - C++: the standard library (through C++23) has no thread pool class. Boost.Asio provides
boost::asio::thread_pool(posttasks to it, thenjoin), and many codebases write a small pool fromstd::thread,std::mutexandstd::condition_variablelike the implementation below. - Node.js: JavaScript runs on one thread, but libuv keeps a thread pool for work the OS cannot do asynchronously: file system calls,
dns.lookup, somecryptofunctions such aspbkdf2andscrypt, andzlib. Its default size is 4, set with theUV_THREADPOOL_SIZEenvironment variable.worker_threadsgives you threads for your own CPU-heavy code. - .NET: the process-wide
ThreadPool, used byTask.Runand async continuations. It adds and removes threads at run time with a hill-climbing algorithm, and each worker has a local queue with work stealing.
When to use it, and when not to
Use a thread pool when
- Many independent, short-to-medium tasks arrive over time (requests, jobs, messages)
- You need a hard cap on concurrent threads, and a place to queue, reject or measure work
- Thread creation would be a noticeable part of each task's cost
- You want one switch to shut all background work down cleanly
Think twice when
- Tasks block on I/O most of the time and virtual threads or async I/O are available
- Tasks wait for other tasks in the same pool (risk of starvation deadlock)
- A task runs for the life of the program: give it a dedicated thread
- Order matters across tasks: a single-threaded executor or a queue per key is simpler
Thread pool vs similar patterns
| Pattern | What it reuses or decouples | Who runs the work | Typical use |
|---|---|---|---|
| Thread pool | Threads; submitting from running | Any of N workers, in any order | Servers, background jobs |
| Producer-Consumer | Producers from consumers, through a bounded buffer | Dedicated consumer threads | Pipelines, logging |
| Object Pool | Expensive objects (connections, buffers) | The borrowing thread itself | Database connection pools |
| Active Object | A caller from one object's method execution | One scheduler thread per object | Serializing access to one object |
| Future & Promise | A result from the code that computes it | Whatever thread completes it | The handle a pool's submit returns |
Implementation
The visualizer's pool: 2 workers, a task queue of capacity 2, the caller-runs policy when it is full, and a shutdown that lets queued tasks finish and wakes every idle worker. Java configures the real ThreadPoolExecutor that way (prestarting the core threads, like the visualizer). Python's ThreadPoolExecutor has an unbounded queue, so the demo bounds it with a semaphore, which makes callers wait instead of running the task. C++ has no standard pool, so it is written out with std::thread, std::mutex, std::condition_variable and a stop flag, exactly the visualizer's code. JavaScript runs on one thread, so the TypeScript version is an async task pool that limits how many tasks run at once; it shows the same queue, idle workers, caller runs and shutdown, but the tasks interleave at await points rather than run in parallel. Output order can vary between runs in every language.
import threading
import time
from concurrent.futures import ThreadPoolExecutor
# ThreadPoolExecutor's queue is unbounded, so bound it ourselves:
# a caller must take a slot before submitting and the slot is given
# back when the task finishes. Callers wait instead of running tasks.
MAX_WORKERS, QUEUE_CAP = 2, 2
slots = threading.BoundedSemaphore(MAX_WORKERS + QUEUE_CAP)
def task(name: str) -> str:
time.sleep(0.1) # a slow call
return f"{name} ran on {threading.current_thread().name}"
def submit(pool: ThreadPoolExecutor, name: str):
slots.acquire() # blocks while 2 run and 2 wait
future = pool.submit(task, name)
future.add_done_callback(lambda _: slots.release())
return future
def main() -> None:
with ThreadPoolExecutor(max_workers=MAX_WORKERS,
thread_name_prefix="W") as pool:
futures = [submit(pool, f"t{i}") for i in range(1, 7)]
for f in futures:
print(f.result()) # result() re-raises a task's exception
# Leaving the with block calls pool.shutdown(wait=True).
print("all workers exited")
if __name__ == "__main__":
main()Key takeaways
- A thread pool runs many tasks on a few long-lived workers that take them from a shared queue: thread creation is paid once, and the pool size caps how many threads exist.
- In the visualizer, thread per task starts 4 threads for 4 tasks and breaks the 2-thread bound at step 6 of a burst; the pool creates 2 threads under every schedule.
- Bound the queue and choose a rejection policy. Caller runs slows submitters down without dropping work; abort fails fast; an unbounded queue only hides overload until memory runs out.
- Shutdown must wake every idle worker (
signalAllor one poison pill per worker). Withsignal(), the visualizer's Idle at shutdown run deadlocks at step 45. - Size CPU-bound pools at about the core count and I/O-bound pools with
N_cpu × U_cpu × (1 + W/C), then measure. For blocking I/O on Java 21, virtual threads plus a semaphore often replace the pool.
Common pitfalls
- Using
Executors.newFixedThreadPoolfor unbounded input: itsLinkedBlockingQueuehas no practical limit, so when workers fall behind the queue grows until the JVM runs out of memory. Build aThreadPoolExecutorwith a bounded queue instead. - Tasks that wait for other tasks in the same pool: if every worker blocks on a future whose task is still queued behind them, nothing can run it (thread starvation deadlock). Use a separate pool, or compose futures instead of blocking.
- Losing exceptions with
submit: the exception is stored in the returnedFutureand only surfaces when someone callsget(). If nobody does, the failure vanishes. Withexecute, it reaches the thread's uncaught exception handler instead. - Leaking
ThreadLocalstate: workers are reused, so a value set by one task is still there for the next one (a user id, a transaction, a large buffer). Clear it in afinallyblock. - Forgetting to shut the pool down: non-daemon workers keep the JVM alive, and a pool created per request leaks threads.
Interview tips
- Walk through
ThreadPoolExecutor.execute: below core size start a thread, else queue, else grow to max, else reject. Then explain why a fixed pool with an unbounded queue never grows past core size. - Be ready to size a pool out loud: CPU-bound about
N_cpu + 1; I/O-boundN_cpu × U_cpu × (1 + W/C); and point out that the database's connection limit may be the real cap. - If asked to implement one, write it as producer-consumer: a queue, a lock, a
notEmptycondition, workers in awhileloop, and a shutdown flag withsignalAll. Mention rejection, exception handling andshutdownvsshutdownNow.
Real-world applications
- Web and RPC servers: a fixed pool of request handler threads (Tomcat's connector, gRPC executors).
- Background job runners and schedulers: email sending, report generation, periodic cleanup.
- Parallel computation: Java parallel streams and
CompletableFutureon the commonForkJoinPool. - Runtimes: Node's libuv pool for file system and DNS work, the .NET thread pool behind
Task.Run. - Clients of rate-limited services: a small pool caps concurrent calls to a downstream API.
Test yourself
In the visualizer's Burst run, the queue holds t1 and t2 when S calls execute(t3). What happens to t3?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.