Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Video lesson · Chapter 1 of 6
Make a prediction
Thread pool
1:03Reel
Theory
Read or listen first. About 2 min.
What it is
A thread pool is a group of worker threads that live for a long time and run many tasks, one after another. Tasks wait in a queue. Whoever has work submits it and gets a future for the result. Submission and execution are separate: the caller says what to do, the pool decides when and on which thread.
Inside, every pool is the same loop: wait until the queue has something, take it, run it, go back. Everything else is about the edges: how many workers, how long the queue, what if it is full, what if a task fails, how to stop.
It is a pattern made of other patterns. A task is a command, the queue makes it a producer-consumer, the result is a future, and the answer to a full queue is a strategy.
Why it exists
To reuse threads. Creating one costs time and memory, and for short tasks this can be more than the task itself.
To limit. A server that starts a thread per request has no defense against a burst. A pool has two numbers that say how much runs and how much waits.
To separate concerns. The code that has work does not create, name, count or stop threads. One object does, and it can be configured, measured and closed.
A short history
1999
Robert Blumofe and Charles Leiserson publish Scheduling Multithreaded Computations by Work Stealing in the Journal of the ACM.
2000
Doug Lea presents A Java Fork/Join Framework, a pool with work stealing written in Java.
2004
JSR 166 is final. Java 5 brings
java.util.concurrentwithExecutorServiceandThreadPoolExecutor.2011
Java 7 includes
ForkJoinPool, and Python 3.2 addsconcurrent.futureswithThreadPoolExecutor.2023
Java 21 makes virtual threads final (JEP 444) and advises never to pool them.
Words to know
- Worker
- A thread of the pool that runs tasks in a loop.
- Task
- A piece of work as an object, so that it can wait.
- Bounded queue
- A queue with a limit. Full is a state that the design answers.
- Rejection policy
- What happens to a task that does not fit.
- Backpressure
- Slowing the source down when the receiver cannot keep up.
- Core and maximum
- Workers that stay, and workers allowed in a rush.
- Keep alive
- How long an extra worker may be idle before it ends.
- Work stealing
- Idle workers take tasks from the queues of others.
- Starvation of the pool
- All workers wait for tasks that have no worker.
- Bulkhead
- Separate pools, so that one kind of work cannot take all threads.
- Poison pill
- A special task that tells a worker to leave.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Submit. A task goes into the queue, a future comes back.
Understand it
Start here
Shearing day
A program has a thousand small jobs. It could start a thousand threads. A thread pool keeps a few threads, lets them live, and hands them one job after another from a queue. It saves the cost of starting threads, and much more important, it puts a limit on how much runs at once.
Everything in a thread pool is in this barn: workers, queue, limit, refusal, result, failure, closing time.
Why
What is wrong with a thread per task?
import threadingdef serve(requests, handle): for r in requests: threading.Thread(target=handle, args=(r,)).start()Four costs
| Cost | Why | What the pool does |
|---|---|---|
| Starting | The system must create the thread and its stack. Measure it on your machine: it is often tens of microseconds, and more under load | Starts each worker once |
| Memory | Each thread reserves a stack, 8 MB for the threads of libuv, for example. Only the used part takes real memory | A fixed number of stacks |
| Switching | More running threads than cores means turns, and cold caches | About as many as can run |
| No limit | Every user opens a thread, a connection, a file. Something runs out | A limit that you chose, and an answer when it is reached |
One queue, a few loops
Parts
Who does what
Five participants
ThreadPool
The manager. Creates the workers, takes tasks, knows whether it is closed. In libraries:
ThreadPoolExecutorin Java and Python, behind the interfaceExecutorServicein Java.WorkerThread
A thread that lives long. Its loop takes a task, runs it, and repeats.
Thread,Worker,std::thread.TaskQueue
The thread-safe waiting place. Blocks workers when it is empty and refuses or blocks callers when it is full.
BlockingQueue,queue.Queue.Task
A unit of work as an object, so that it can wait in a queue.
Runnable(no result),Callable<T>(result, may throw), any function. This is the command pattern.Future
The receipt. Ask if it is done, wait for the value, wait with a limit, cancel. Its own page: future and promise.
Bad: each service starts its own threads
1/2One service
Start a thread for each mail. It works on the first day.
depends on
Good: the pool owns threads, queue and limit
1/5The manager
Clients know one object and one call. All decisions about threads are behind it.
usesowns (dies together)depends on
In motion
From submit to result
Two workers, three tasks
Waiting for a result, with and without patience
Six moments in the life of a pool
| Moment | What happens | Remember |
|---|---|---|
| Create | Workers start and block on take, or they start with the first tasks | Java's ThreadPoolExecutor starts core threads only when tasks arrive, unless you call prestartAllCoreThreads |
| First submit | Task and future are wrapped, queued, taken by a sleeping worker | The caller has the future before the task ends |
| Many submits | All workers busy, the rest waits in order | Waiting tasks are memory |
get() | Blocks until done. Throws what the task threw, wrapped in ExecutionException in Java | An already finished future answers at once |
get(timeout) | Gives up the waiting after a while | Needed where the caller has a deadline |
| Shutdown | No new tasks, old ones finish, workers leave | Then wait with awaitTermination |
A worker is always in one of these places
Kinds
Pool types, and the queue behind each
The pools of `java.util.concurrent`
| Pool | Workers | Queue | Good for | Danger |
|---|---|---|---|---|
newFixedThreadPool(n) | n | Without a limit | Steady work, CPU-bound tasks | The queue can grow until memory ends |
newCachedThreadPool() | 0 to very many, idle ones end after 60 s | None, direct handover | Many short tasks, a known load | Threads without a limit |
newScheduledThreadPool(n) | n | Ordered by time | After a delay, every minute | A long task delays others |
newWorkStealingPool() | One per processor by default | One per worker | Tasks that split into tasks | No promise about the order |
newSingleThreadExecutor() | 1 | Without a limit | Strict order without locks | One slow task stops all |
newVirtualThreadPerTaskExecutor() | A virtual thread per task | None | Many tasks that wait (Java 21) | No limit by itself |
Queues
| Queue in Java | In Python | Behaviour |
|---|---|---|
LinkedBlockingQueue without a number | Queue() | No limit in practice: put never waits |
ArrayBlockingQueue(100) | Queue(maxsize=100) | Bounded: gives backpressure |
PriorityBlockingQueue | PriorityQueue() | Smallest first. Low ranks may starve |
SynchronousQueue | none | No places: each put waits for a take |
LinkedBlockingDeque as a stack | LifoQueue() | Newest first. Good under overload when old work is worthless |
put waits, offer answers false, take waits, poll answers null. With a time limit the last two pairs meet in the middle.BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);ThreadPoolExecutor pool = new ThreadPoolExecutor( 8, // core: workers we keep 16, // most: only reached when the queue is full 60, TimeUnit.SECONDS, // idle time of an extra worker queue, new ThreadPoolExecutor.CallerRunsPolicy());queue.offer(task); // false if fullqueue.offer(task, 1, TimeUnit.SECONDS);Runnable next = queue.poll(); // null if empty// put and take waitfrom queue import Empty, Full, LifoQueue, PriorityQueue, Queuefifo, bounded, by_rank, stack = Queue(), Queue(maxsize=2), PriorityQueue(), LifoQueue()bounded.put("a"); bounded.put("b")try: bounded.put("c", block=False)except Full: print("full")for rank, name in ((3, "low"), (1, "high")): by_rank.put((rank, name))print(by_rank.get())stack.put("old"); stack.put("new")print(stack.get())try: fifo.get(timeout=0.01)except Empty: print("empty")bounded.get(); bounded.task_done()task_done and join tell you when all that was put has been handled.How many
Size: two formulas and one measurement
Tasks that compute
Tasks that wait
Both are starting points. The formula looks at the processor only. If each of the 80 tasks needs a database connection and the database takes 20, then 60 workers wait for a connection. The smallest resource decides. Then measure, with the real load.
How many are busy?
Use it
Client code in three languages
from concurrent.futures import ThreadPoolExecutor, as_completedimport timedef process(task_id): time.sleep(0.02) return f"result of task {task_id}"with ThreadPoolExecutor(max_workers=3) as pool: futures = {pool.submit(process, i): i for i in range(1, 7)} for f in as_completed(futures): # in the order they finish try: f.result() except Exception as e: print(f"task {futures[f]} failed: {e}") print([f.result() for f in futures]) # in the order they were submittedprint("pool is closed")with block waits for all tasks.ExecutorService pool = Executors.newFixedThreadPool(3);List<Callable<String>> tasks = new ArrayList<>();for (int i = 1; i <= 6; i++) { int id = i; tasks.add(() -> "result of task " + id + " on " + Thread.currentThread().getName());}List<Future<String>> futures = new ArrayList<>();for (Callable<String> t : tasks) futures.add(pool.submit(t));for (Future<String> f : futures) System.out.println(f.get(10, TimeUnit.SECONDS));List<Future<String>> all = pool.invokeAll(tasks); // returns when all are donepool.shutdown();if (!pool.awaitTermination(60, TimeUnit.SECONDS)) pool.shutdownNow();execute is fire and forget, submit gives a future, invokeAll waits for a whole list.async function runLimited<T>(tasks: (() => Promise<T>)[], limit: number): Promise<T[]> { const results = new Array<T>(tasks.length); let next = 0; const worker = async () => { while (next < tasks.length) { const i = next++; // no await between the check and this line results[i] = await tasks[i](); } }; await Promise.all(Array.from({ length: limit }, worker)); return results;}const tasks = [1, 2, 3, 4, 5, 6].map((id) => async () => { await new Promise((done) => setTimeout(done, 20)); return "result of task " + id;});console.log(await runLimited(tasks, 3));For work that computes, Node.js has worker_threads and browsers have Web Workers. Each is a real thread with its own memory, and they talk by messages. The Node.js manual says it too: use a pool of them, because starting one per task costs more than it brings. The worker's side of such a pool is a loop again: a message comes in, the answer goes out.
import { parentPort } from "node:worker_threads";parentPort?.on("message", async ({ id, data }) => { try { parentPort!.postMessage({ id, ok: true, result: await compute(data) }); } catch (e) { parentPort!.postMessage({ id, ok: false, error: String(e) }); // the worker lives on }});self.onmessage and self.postMessage.Choose
When to use one and when not
A pool fits
- Many short tasks
- Requests of a web server
- Blocking calls to a database or a file
- Splitting data into parts and computing them
- Background jobs
A pool hurts
- Tasks that block for hours: each takes a worker for good. Give them their own thread
- Tasks that rely on data left in a thread-local
- Tasks with a strict order, unless one worker handles each key
- Work without a limit and without backpressure
- Tasks that wait for other tasks in the same pool
Which kind of pool?
The queue of your pool is full. What happens to the next task?
BreaksNo limit, so it is never full
- How
- An unbounded queue.
- Limit
- Memory fills, waiting times grow, and callers get answers to questions they have forgotten.
- Choose when
- Never in a server.
WorksRefuse
- How
- Raise an error at once. The caller says: busy, try later.
- Limit
- The caller must handle it.
- Choose when
- The default for requests: fail fast, and tell the truth.
WorksDrop the oldest
- How
- Throw away the task that has waited longest.
- Limit
- Its future must be told, and data is lost.
- Choose when
- Only the newest matters: a screen refresh, a sensor value.
StrongSlow the caller down, with a limit
- How
- Caller runs, or wait a short time and then refuse.
- Limit
- Never in a thread that must not block, such as an event loop.
- Choose when
- Batch work and pipelines, where the source can wait.
Summary
The whole topic in one minute.
A thread pool runs many tasks on a few threads that stay alive. A caller submits a task, gets a future, and goes on. Each worker sleeps on the queue, takes a task, runs it outside the lock, stores the result or the error, and takes the next.
The numbers come from the work: cores + 1 for computing, cores x (1 + W/C) for waiting, cut down to the scarcest resource. The queue length is the patience of the caller in seconds times the tasks per second.
The hard part is at the edges. Choose who pays when the queue is full, never wait inside a worker for a task of the same pool, clear what sticks to a thread, read every future, and close in steps with a limit.
- The pool manages workers and a queue. Workers loop: take, run, repeat.
- The queue has a limit, and the overflow has an answer that you chose.
submitreturns a future at once. It carries the value or the exception.- A failing task must not kill its worker. An idle worker must be woken to leave.
- Compute: cores + 1. Wait: cores x (1 + W/C), then the smallest resource decides.
- Close in two steps: stop accepting, finish, and cancel what is left after a limit.
- Never wait in a worker for a task of the same pool.
Sources
- Java API: ThreadPoolExecutor
- Java API: ExecutorService
- Java API: ForkJoinPool
- JEP 444: virtual threads
- Python: concurrent.futures
- JSR 166: Concurrency Utilities
- Doug Lea: A Java Fork/Join Framework
- Tokio: runtime
- libuv: thread pool
- Node.js: worker threads
- Apache Tomcat: HTTP connector
- nginx: core functionality, thread_pool
- .NET: the managed thread pool