Multithreading Patterns
Locks, atomics and condition variables are the raw parts. Real programs rarely use them one at a time. They use a handful of patterns built from those parts, and the same handful shows up again and again: a pool of worker threads, a future you wait on, a batch of calls sent out in parallel and gathered back, a cache that many threads read and few write, an object nobody can change, data that only one thread ever touches.
Knowing these shapes saves you from reinventing them under interview pressure. Each one is also a way to need fewer locks, which means fewer bugs. This post walks through them in the order you are likely to need them, starting from the naive code each one replaces.
💡 Why this matters in an interview: "use a thread pool," "return a future," "make it immutable" and "only the writer thread touches it" are one-sentence answers that remove whole classes of bugs. Interviewers reward picking the right shape far more than hand-written locking.
Thread Pools
Say an image service needs to generate a thumbnail for every uploaded photo. The first version starts a thread per upload:
def on_upload(photo_id: str) -> None:
threading.Thread(target=make_thumbnail, args=(photo_id,)).start()
This works for ten uploads. With ten thousand arriving in a burst, it starts ten thousand threads. Each one costs memory for its stack and time to create, and the operating system spends more time switching between them than running them. Eventually the process runs out of memory or threads.
A thread pool fixes this with a fixed set of worker threads and a queue of tasks. Submitting a task puts it in the queue; an idle worker takes it and runs it. Ten thousand uploads become ten thousand queued tasks served by, say, eight threads.
from concurrent.futures import ThreadPoolExecutor
pool = ThreadPoolExecutor(max_workers=8)
def on_upload(photo_id: str) -> None:
pool.submit(make_thumbnail, photo_id) # queued; a worker runs it later
ExecutorService pool = Executors.newFixedThreadPool(8);
void onUpload(String photoId) {
pool.submit(() -> makeThumbnail(photoId));
}
Three decisions make a pool production-ready:
- Size. For CPU-bound work (resizing, parsing), about one thread per core; more threads only add switching.
For I/O-bound work (HTTP calls, database queries), threads spend most of their time waiting, so you can use many
more. A common rule of thumb is
cores × (1 + wait time / compute time). - Queue bound.
Executors.newFixedThreadPooluses an unbounded queue, so a flood of tasks fills memory instead of failing. In production, use a bounded queue and decide what happens when it is full: reject with an error, make the caller run the task itself (CallerRunsPolicy, which slows the producer down), or drop the oldest task. This is backpressure. - Shutdown.
shutdown()stops accepting tasks and lets queued ones finish;shutdownNow()interrupts running ones. Call one of them, or the pool's threads keep the program alive.
⚠️ Common mistake: a task that submits another task to the same pool and then blocks waiting for it. If every worker does that at once, all workers are waiting and nobody is left to run the inner tasks: a thread starvation deadlock. Use a separate pool for nested work, or chain futures instead of blocking (next section).
Design a Thread Pool builds one from a blocking queue and worker threads, with futures, shutdown and rejection.