Thread Pools
Why pools exist, how Java's ThreadPoolExecutor decides between a new thread, the queue and rejection, how to size a pool from the wait-to-compute ratio, and a small pool built and tested in Python.
Overview
A thread pool keeps a fixed set of worker threads and a queue of tasks. Callers submit tasks; idle workers take them from the queue and run them; results come back through a future. The threads live for the life of the pool instead of one per task.
A pool buys three things. Creating and destroying a thread for every task costs time and memory, and the pool pays it once. The number of workers caps how much runs at once, so a burst of requests cannot create thousands of threads. And the queue gives overload a place to show up, as a growing queue, where you can measure it and push back.
The shape of a pool
Every pool has the same four parts: callers, a bounded task queue, a set of workers, and a future for each task. The figure shows how a task moves through them.
In Python the standard pool is concurrent.futures.ThreadPoolExecutor. Its submit returns a Future; result(timeout) waits for the value and re-raises the task's exception if it failed; using the executor in a with block shuts it down and waits for pending work. Since Python 3.8 the default max_workers is min(32, os.cpu_count() + 4) (3.13 uses os.process_cpu_count()).
Key concepts
- Worker reuse
- Bounded concurrency
- Task queue
- Futures
- Core and maximum size
- Rejection policy
- Pool sizing
- Graceful shutdown
Interview questions
- How do you size a thread pool?
- What happens when a thread pool is full? Compare the rejection policies.
- How do you shut down a thread pool cleanly?
- Implement a simple thread pool.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio