AlgoViz

Thread pool

medium 70 min

A 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

0:00 / 5:06

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

  1. 1999

    Robert Blumofe and Charles Leiserson publish Scheduling Multithreaded Computations by Work Stealing in the Journal of the ACM.

  2. 2000

    Doug Lea presents A Java Fork/Join Framework, a pool with work stealing written in Java.

  3. 2004

    JSR 166 is final. Java 5 brings java.util.concurrent with ExecutorService and ThreadPoolExecutor.

  4. 2011

    Java 7 includes ForkJoinPool, and Python 3.2 adds concurrent.futures with ThreadPoolExecutor.

  5. 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.

Step 1 of 4

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.

Three shearers and a pen
SHEARING1 sheep, 1 new shearer,again and again

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?

Python
import threadingdef serve(requests, handle):    for r in requests:        threading.Thread(target=handle, args=(r,)).start()
Simple, and fine for three tasks. With ten thousand it starts ten thousand threads.

Four costs

CostWhyWhat the pool does
StartingThe system must create the thread and its stack. Measure it on your machine: it is often tens of microseconds, and more under loadStarts each worker once
MemoryEach thread reserves a stack, 8 MB for the threads of libuv, for example. Only the used part takes real memoryA fixed number of stacks
SwitchingMore running threads than cores means turns, and cold cachesAbout as many as can run
No limitEvery user opens a thread, a connection, a file. Something runs outA limit that you chose, and an answer when it is reached
The last row is the real reason. Starting a thread has become cheap. Having no limit has not.

One queue, a few loops

A thread pool is a producer-consumer whose items are pieces of work.

Parts

Who does what

Five participants

  • ThreadPool

    The manager. Creates the workers, takes tasks, knows whether it is closed. In libraries: ThreadPoolExecutor in Java and Python, behind the interface ExecutorService in 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

MailService+ send(): new ThreadThread- stack- one job, then dead

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

Client+ submits tasksThreadPool- workers: List<WorkerThread>- queue: BlockingQueue<Task>- isShutdown: bool+ submit(task): Future<T>+ execute(task)+ shutdown()

1/5The manager

Clients know one object and one call. All decisions about threads are behind it.

usesowns (dies together)depends on

Draw at least pool, worker and queue, with the filled diamonds. Then say the worker loop aloud.

In motion

From submit to result

Two workers, three tasks

The client is never blocked by a running task. Task 3 waits until a worker is free, and nobody starts a thread for it.

Waiting for a result, with and without patience

A timeout ends the waiting and not the work. Decide: wait again, cancel, or answer without it.

Six moments in the life of a pool

MomentWhat happensRemember
CreateWorkers start and block on take, or they start with the first tasksJava's ThreadPoolExecutor starts core threads only when tasks arrive, unless you call prestartAllCoreThreads
First submitTask and future are wrapped, queued, taken by a sleeping workerThe caller has the future before the task ends
Many submitsAll workers busy, the rest waits in orderWaiting tasks are memory
get()Blocks until done. Throws what the task threw, wrapped in ExecutionException in JavaAn already finished future answers at once
get(timeout)Gives up the waiting after a whileNeeded where the caller has a deadline
ShutdownNo new tasks, old ones finish, workers leaveThen wait with awaitTermination

A worker is always in one of these places

A failed task leads back to Idle, not to the end. If it leads to the end, your pool loses a worker with each bug.

Kinds

Pool types, and the queue behind each

The pools of `java.util.concurrent`

PoolWorkersQueueGood forDanger
newFixedThreadPool(n)nWithout a limitSteady work, CPU-bound tasksThe queue can grow until memory ends
newCachedThreadPool()0 to very many, idle ones end after 60 sNone, direct handoverMany short tasks, a known loadThreads without a limit
newScheduledThreadPool(n)nOrdered by timeAfter a delay, every minuteA long task delays others
newWorkStealingPool()One per processor by defaultOne per workerTasks that split into tasksNo promise about the order
newSingleThreadExecutor()1Without a limitStrict order without locksOne slow task stops all
newVirtualThreadPerTaskExecutor()A virtual thread per taskNoneMany tasks that wait (Java 21)No limit by itself
Fixed, cached, scheduled, stealing: four old names to know. In an interview say the missing limit of the first two before you are asked.

Queues

Queue in JavaIn PythonBehaviour
LinkedBlockingQueue without a numberQueue()No limit in practice: put never waits
ArrayBlockingQueue(100)Queue(maxsize=100)Bounded: gives backpressure
PriorityBlockingQueuePriorityQueue()Smallest first. Low ranks may starve
SynchronousQueuenoneNo places: each put waits for a take
LinkedBlockingDeque as a stackLifoQueue()Newest first. Good under overload when old work is worthless
Four verbs: put waits, offer answers false, take waits, poll answers null. With a time limit the last two pairs meet in the middle.
Java
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 wait
The constructor behind the factory methods. A bounded queue and a chosen answer for the overflow.
Python
from 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()
The same verbs in Python. task_done and join tell you when all that was put has been handled.
Edit and run it in your browser

How many

Size: two formulas and one measurement

Tasks that compute

Nthreads=Ncpu+1N_{threads} = N_{cpu} + 1
More threads than cores only take turns. The extra one fills in when another is stopped for a moment, for example by a page fault.

Tasks that wait

Nthreads=Ncpu×U×(1+WC)N_{threads} = N_{cpu} \times U \times \left(1 + \frac{W}{C}\right)
W is the waiting time, C the computing time, U the share of the processor you want to use (1 for all of it). With 8 cores, 90 ms of waiting and 10 ms of computing: 8 x (1 + 9) = 80.

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?

L=λ×SL = \lambda \times S
Little's law: tasks per second times seconds per task is the number in progress. 200 tasks per second at 0.1 s each keep 20 workers busy on average. With fewer than 20 the queue grows without end.

Use it

Client code in three languages

Python
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")
Six tasks on three workers. Leaving the with block waits for all tasks.
Edit and run it in your browser
Java
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.
TypeScript
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));
JavaScript code runs in one thread, so this is a limiter for tasks that wait. Results keep the order of the input.

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.

TypeScript
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  }});
The worker side in Node.js. In a browser the same two lines read 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?

Separate pools for separate kinds. Slow reports should not be able to take all the workers of quick clicks: a bulkhead.

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.
  • submit returns 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