Thread Pool Pattern
Reuse a fixed set of threads for short-lived tasks instead of creating a new thread per task. Reduces overhead and bounds resource usage under load.
Overview
Creating a thread is expensive — each one allocates a stack (typically 1MB), needs kernel-level setup, and adds scheduling overhead. When tasks are short-lived and frequent, a thread-per-task design wastes memory and can collapse under load. The Thread Pool pattern keeps a fixed set of worker threads around: tasks go into a queue, and whichever worker finishes first picks up the next one.
When to Use
- You’ve got many short-lived tasks that run concurrently
- Creating a thread per task is too expensive (high throughput, short duration)
- You need to bound the number of concurrent threads to protect resources
- You want to control queueing behavior when all threads are busy
For workloads where actors and message passing fit better, see the Actor Model Pattern.
Solution
Python (concurrent.futures)
from concurrent.futures import ThreadPoolExecutor, as_completed
import requests
def fetch_url(url):
response = requests.get(url, timeout=5)
return {"url": url, "status": response.status_code, "length": len(response.content)}
urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/3",
"https://httpbin.org/delay/1",
]
# Pool with 3 threads: at most 3 requests run concurrently
with ThreadPoolExecutor(max_workers=3) as executor:
futures = {executor.submit(fetch_url, url): url for url in urls}
for future in as_completed(futures):
url = futures[future]
try:
result = future.result()
print(f"{result['url']}: {result['status']} ({result['length']} bytes)")
except Exception as e:
print(f"{url}: FAILED - {e}")
JavaScript (workerpool — Node.js)
// worker.js — runs in a separate thread
import workerpool from "workerpool";
workerpool.worker({
fetchUrl(url) {
return fetch(url)
.then((res) => res.text())
.then((text) => ({ url, length: text.length }));
},
});
// main.js
import workerpool from "workerpool";
import { fileURLToPath } from "url";
import path from "path";
const __filename = fileURLToPath(import.meta.url);
const pool = workerpool.pool(path.join(path.dirname(__filename), "worker.js"), {
minWorkers: 2,
maxWorkers: 4,
});
const urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/3",
"https://httpbin.org/delay/1",
];
async function fetchAll() {
const promises = urls.map((url) => pool.exec("fetchUrl", [url]));
const results = await Promise.all(promises);
results.forEach((r) => console.log(`${r.url}: ${r.length} bytes`));
await pool.terminate();
}
fetchAll();
Java (ExecutorService)
import java.util.concurrent.*;
import java.util.List;
import java.util.ArrayList;
import java.time.Duration;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.URI;
import java.net.http.HttpResponse;
public class ThreadPoolExample {
private static final HttpClient client = HttpClient.newHttpClient();
public static String fetchUrl(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.timeout(Duration.ofSeconds(5))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return url + ": " + response.statusCode() + " (" + response.body().length() + " bytes)";
}
public static void main(String[] args) throws Exception {
String[] urls = {
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/3",
"https://httpbin.org/delay/1"
};
// Pool with 3 threads
ExecutorService pool = Executors.newFixedThreadPool(3);
List<Future<String>> futures = new ArrayList<>();
for (String url : urls) {
futures.add(pool.submit(() -> fetchUrl(url)));
}
for (Future<String> future : futures) {
try {
System.out.println(future.get(10, TimeUnit.SECONDS));
} catch (Exception e) {
System.out.println("FAILED: " + e.getMessage());
}
}
pool.shutdown();
}
}
Explanation
The pool spins up a fixed number of workers before any work arrives. A submitted task lands in the queue; whichever worker goes idle next grabs it, runs it, and comes back for the one after. Three things fall out of that:
- No creation overhead: threads are created once at pool startup and reused
- Bounded resources: the pool size caps how many threads run at once, so memory can’t be exhausted by task volume
- Backpressure: when every worker is busy, new tasks queue up instead of spawning unbounded threads
Pool size is the key tuning parameter. CPU-bound tasks want roughly one thread per core; I/O-bound tasks can run more because threads spend their time waiting. Brian Goetz’s Java Concurrency in Practice gives the classic sizing formula (N * U * (1 + W/C)), and the JDK’s ThreadPoolExecutor docs document the queue and rejection-policy mechanics. For a worksheet that turns those numbers into concrete settings, see the Thread Pool Sizing Template. If you’re submitting tasks one by one and want a simpler API, the thread pools recipe covers the everyday cases.
Variants
| Variant | Pool Type | Use Case | Tradeoff |
|---|---|---|---|
| Fixed Pool | N threads, unbounded queue | Predictable load | Queue can grow without limit |
| Cached Pool | 0 to N threads, SynchronousQueue | Many short-lived tasks | Unbounded thread creation |
| Scheduled Pool | N threads, delayed queue | Periodic and delayed tasks | More complex scheduling |
| Bounded Pool | N threads, bounded queue | Memory-safe under load | Rejection when queue full |
| Work Stealing | Per-thread queues with stealing | Fork-join recursive tasks | More overhead, complex |
What Works
- Size the pool to the workload: CPU-bound ≈ core count, I/O-bound can go higher
- Use a bounded queue to prevent memory exhaustion under load
- Set a rejection policy (abort, caller-runs, discard) for when the queue fills up
- Name pool threads — you’ll thank yourself when reading thread dumps
- Always shut down the pool in
finallyor try-with-resources - Monitor pool metrics: active threads, queue depth, task latency
- Use one shared pool per application instead of a pool per request; for code that hands work to a queue like the one above, the Producer-Consumer Pattern is the natural companion
Common Mistakes
- Pool too large: too many threads cause context-switching overhead and memory waste. More threads doesn’t mean faster.
- Pool too small: tasks queue up and latency climbs. For I/O tasks, a small pool caps throughput.
- Unbounded queue: tasks pile up in memory when producers outpace consumers. Use a bounded queue.
- Blocking tasks in the pool: a task that blocks forever (infinite loop, deadlock) holds a worker hostage. Set timeouts.
- Not shutting down the pool: threads keep running and the JVM never exits. Always call
shutdown(). - Long-running tasks in a shared pool: they starve the short tasks. Move them to a dedicated pool.
Troubleshooting
- Queue depth grows and never drains: workers are too few or tasks are too slow — check task latency first, then resize the pool or split long tasks into a separate pool.
RejectedExecutionExceptionstorms: the bounded queue is full and producers won’t slow down. Switch toCallerRunsPolicyfor natural backpressure, or shed load upstream.- Tasks submitted but never run: a worker is stuck on a blocking call. Take a thread dump and look for parked pool threads; add timeouts to the offending call.
- Pool threads still alive at shutdown:
shutdown()doesn’t interrupt running tasks — callawaitTermination()with a deadline and fall back toshutdownNow()if needed. - Throughput flat after increasing pool size: you’ve hit a different bottleneck (CPU, lock contention, downstream service). Measure before adding more threads.
Advanced Topics
Scenario: custom pool with worker_threads
Sometimes the built-in abstractions don’t fit — here’s a minimal pool over Node’s worker_threads. Tasks are posted to real workers; idle workers pick from a shared queue.
// thread-pool.ts — minimal pool over Node worker_threads
import { Worker } from "worker_threads";
type Task = { id: number; payload: unknown };
type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void };
export class ThreadPool {
private workers: Worker[] = [];
private taskQueue: { task: Task; pending: Pending }[] = [];
private inFlight = new Map<number, Pending>();
private idleWorkers: number[] = [];
constructor(private size: number, private workerFile: string) {
for (let i = 0; i < size; i++) {
const worker = new Worker(workerFile);
const workerId = i;
worker.on("message", (result: { id: number; value: unknown }) => {
this.inFlight.get(result.id)?.resolve(result.value);
this.inFlight.delete(result.id);
this.idleWorkers.push(workerId);
this.processQueue();
});
worker.on("error", (err) => {
this.idleWorkers.push(workerId);
this.processQueue();
});
this.workers.push(worker);
this.idleWorkers.push(i);
}
}
submit<T>(payload: unknown): Promise<T> {
return new Promise((resolve, reject) => {
const task: Task = { id: Date.now() + Math.random(), payload };
this.taskQueue.push({ task, pending: { resolve: resolve as (v: unknown) => void, reject } });
this.processQueue();
});
}
private processQueue() {
while (this.idleWorkers.length > 0 && this.taskQueue.length > 0) {
const workerId = this.idleWorkers.shift()!;
const { task, pending } = this.taskQueue.shift()!;
this.inFlight.set(task.id, pending);
this.workers[workerId].postMessage(task);
}
}
async shutdown() {
await Promise.all(this.workers.map((w) => w.terminate()));
}
}
// usage.ts — image processing with 4 workers
import { ThreadPool } from "./thread-pool.js";
const pool = new ThreadPool(4, "./image-worker.js");
const results = await Promise.all([
pool.submit({ file: "img1.png", op: "resize", w: 800 }),
pool.submit({ file: "img2.png", op: "resize", w: 800 }),
pool.submit({ file: "img3.png", op: "resize", w: 800 }),
]);
await pool.shutdown();
Pool size tuning, in practice:
| Workload | Pool size | Rationale |
|---|---|---|
| CPU-heavy | CPU cores | One thread per core |
| I/O-heavy | 2x CPU cores | Threads wait on I/O |
| Mixed | CPU cores + 2 | Balance CPU and I/O |
| Image processing | CPU cores | CPU-bound |
| File parsing | 2x CPU cores | I/O + CPU |
Lessons:
- A pool reuses threads and avoids creation overhead
- The task queue buffers work when every worker is busy
- Size it: cores for CPU-heavy, ~2x for I/O-heavy
- Always shut the pool down or you leak workers
- In Node.js,
worker_threadsis for CPU-intensive tasks; for I/O,async/awaiton the event loop is enough
When do I use threads vs async in Node.js?
Reach for worker_threads when the work is CPU-heavy — image processing, crypto, compression, big file parsing — because the event loop is single-threaded and CPU work blocks everything behind it. For I/O (DB, HTTP, file reads) async/await is enough. Rough rule of thumb: under ~10ms of CPU, stay on the event loop; past ~100ms, hand it to a worker.
The runnable companion has the Python pool examples above ready to run — ThreadPoolExecutor with submit/as_completed, bounded queues, and a fake workload so nothing hits the network.
Frequently Asked Questions
How do I choose the right pool size?
For CPU-bound tasks: poolSize = Runtime.getRuntime().availableProcessors(). For I/O-bound tasks: poolSize = N * U * (1 + W/C) where N = cores, U = target utilization, W = wait time, C = compute time — Goetz's formula. In practice, 2-10x cores for I/O tasks.
What happens when the queue is full?
With an unbounded queue — the default in Java's Executors.newFixedThreadPool — tasks pile up until memory runs out. With a bounded queue the rejection policy takes over instead: AbortPolicy throws, CallerRunsPolicy runs the task on the calling thread, DiscardPolicy drops it without a word.
Should I use a thread pool or virtual threads?
Java 21+ virtual threads are ideal for I/O-bound work with high concurrency — they're cheap enough that pooling them is pointless. Keep a thread pool for CPU-bound tasks where you need to bound parallelism.
Can I share a thread pool across components?
Yes, and you should. Creating pools per request or per component wastes resources. Use a single application-wide pool, or a small number of purpose-specific pools (one for CPU tasks, one for I/O).
How do I handle exceptions in pool tasks?
Exceptions thrown by tasks get captured in the Future — call future.get() to retrieve them. For fire-and-forget tasks, install an UncaughtExceptionHandler or override afterExecute on a custom ThreadPoolExecutor.
Related Resources
Producer-Consumer Pattern
Decouple production and consumption with a shared queue. Producers generate items at their own pace; consumers process them through a buffer.
PatternActor Model Pattern: Concurrency Without Shared State
Isolate state in actors that communicate only via messages. Each actor processes one message at a time, eliminating shared-state concurrency bugs by design.
PatternReactive Streams Pattern
Process asynchronous data streams with backpressure. Subscribers request N items at a time, preventing fast producers from overwhelming slow consumers.
PatternAsync Generator Pattern for Lazy Streaming
Stream data lazily with async generators. Yield values one at a time as they become available, enabling memory-efficient processing of large or infinite data sequences.
PatternLock-Free Queue Pattern
Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.
DocThread Pool Sizing Template
Worksheet for documenting thread pool sizing per service: formulas, queue and rejection strategies, and monitoring for Java, Python, Go, and Node.js.