0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Asynchronous I/O
Thread Pools and Executors
Creating a thread for every task is simple and works for small programs, but it collapses under load. Thread pools reuse a fixed set of worker threads to run many short tasks, separating the decision of what work to do from the decision of how many threads to run it on. This section explains the cost of threads, the basic structure of a pool, and the executor abstraction that most languages provide on top of it.
The cost of a thread per task
Every operating system thread costs memory and time. On Linux, a new thread reserves a stack, eight megabytes of virtual address space by default, of which only the touched pages consume physical memory, plus kernel structures for scheduling and signal handling. Creating and destroying a thread takes tens of microseconds, comparable to or longer than many tasks themselves. More importantly, threads compete for cores. If a server creates a thread for each incoming request and receives ten thousand requests per second, it can end up with thousands of runnable threads on a machine with sixteen cores. The scheduler then spends a growing share of time context switching, each switch costing a few microseconds plus the cache misses that follow, and memory use grows with the number of threads. At some load, the server spends more time managing threads than doing work, and adding load makes throughput fall rather than plateau.
The thread per request model also lacks a natural limit. When requests arrive faster than they are served, the number of threads grows until the process runs out of memory or hits a limit on threads, and the failure arrives abruptly under exactly the load the system was meant to handle. A pool turns this cliff into a queue, which can be measured, bounded and shed.
The anatomy of a pool
A thread pool has three parts. A set of worker threads, created once and reused. A task queue, into which callers submit units of work, usually closures or objects with a run method. And a policy that decides how many workers exist, what happens when the queue is full, and how the pool shuts down. Each worker runs a loop: take a task from the queue, blocking if it is empty, run it, and repeat. Submitting a task is just an enqueue, which costs well under a microsecond, so even short tasks are cheap to run on a pool.
Because the workers are reused, any per thread state, such as thread local caches, buffers and database connections bound to a thread, survives across tasks. This is good for performance and a source of bugs when a task leaves thread local state behind that the next task on the same worker sees, such as an unrestored security context, a stale logging context or a leaked transaction.
Executors as an abstraction
Most platforms put an interface above the pool, usually called an executor. Java has the Executor and ExecutorService interfaces, with factory methods such as newFixedThreadPool, newCachedThreadPool and, since Java 21, newVirtualThreadPerTaskExecutor. Python has concurrent.futures with ThreadPoolExecutor and ProcessPoolExecutor. C sharp has the ThreadPool and the Task Parallel Library on top of it. C++ has no standard pool yet, but Boost.Asio thread_pool, Intel oneTBB and Folly executors fill the gap, and the senders and receivers framework planned for C++26 defines a schedulers abstraction. Rust has Rayon for data parallelism and the Tokio runtime for asynchronous tasks.
The value of the abstraction is that code submits work without knowing how it will run. The same code can run on a fixed pool in production, on a single thread in a deterministic test, or on virtual threads after a migration. Executors also return futures, handles that let the caller wait for the result, check for exceptions and cancel the task, which a later lesson covers.
What a pool does not solve
A pool bounds the number of threads, but not the amount of work. If tasks arrive faster than workers finish them, the queue grows, and with an unbounded queue, as in Java newFixedThreadPool, the growth is limited only by memory. Latency rises with queue length, so long before memory runs out, callers see timeouts. A pool also does not make blocking tasks cheap: a task that waits two seconds on a slow database holds a worker for those two seconds, and if every worker is waiting, the pool is idle while work piles up. Sizing, bounding and isolating pools, covered in the next sections, are what make them robust.
Pools for processes, connections and objects
The pooling idea is older and broader than thread pools. Database connection pools keep a set of open connections, because establishing a connection with TLS and authentication can take tens of milliseconds, far longer than a typical query. Process pools, such as Python ProcessPoolExecutor and the prefork model of servers like Gunicorn, keep worker processes alive to avoid the cost of starting an interpreter for every job and to sidestep the global interpreter lock for CPU bound work. Object pools reuse expensive buffers to reduce allocation and garbage collection pressure. All of them share the same design questions as thread pools: how many resources to keep, what callers do when every resource is in use, how to detect and replace broken resources, and how to drain the pool on shutdown. Thread pools and connection pools are also coupled in practice, because each worker that talks to a database usually holds a connection while it runs, so the effective concurrency is the smaller of the two sizes.
A short history of the model
Early servers on Unix forked a process per connection, as the original Apache prefork model and inetd did. Threads made the per connection model cheaper, and Java servers of the late 1990s often created a thread per connection. The C10K problem, described by Dan Kegel in 1999, asked how to handle ten thousand concurrent connections on one machine, and the answers were event driven IO and pools: a few threads multiplexing many connections, with pools for the blocking work that remained. Java 5 added java.util.concurrent in 2004, designed by Doug Lea, which standardized executors, thread pools and futures and became the model that most other languages followed. Virtual threads in Java 21 and goroutines in Go revisit the per request model by making threads cheap enough that the original simple design scales again, while pools remain the right tool for limiting CPU bound work and access to scarce resources.
Cached pools and their risk
Java newCachedThreadPool creates a new thread whenever a task arrives and no idle thread exists, and lets idle threads die after sixty seconds. It works well for bursts of short tasks, but it has no upper bound on threads. Under a sudden surge of slow tasks, it behaves exactly like thread per request and can create thousands of threads, exhausting memory. Cached pools are therefore safe only when the submission rate is naturally limited by something else. For services that accept external traffic, a bounded pool with a bounded queue is the safer default, and the configuration should be explicit, using the ThreadPoolExecutor constructor with a core size, a maximum size, a queue and a rejection policy rather than a convenience factory whose defaults are hidden.
A thread pool reuses a fixed set of workers, which avoids thread creation cost and the collapse of thread per request under load. Callers submit tasks through an executor interface and get futures back. A pool does not bound queued work or make blocking tasks cheap, so queue size, pool size and isolation still need design.