Concurrency Patterns

The three bugs of shared state (races, deadlocks, stale reads) and the patterns that prevent them: locks, thread pools, bounded queues, read-write locks and lock ordering.

Overview

Concurrency questions in a low-level design interview come in one shape: here is some shared state, several threads touch it, make it correct. The answer is never 'add a lock everywhere'. It is naming the bug that can happen, picking the pattern that rules it out, and knowing what the language guarantees.

This topic uses Python and Java. Python examples run; Java examples compile. The guarantees come from the Java Language Specification and the Python and Java library documentation, and each one is cited.

The three bugs

Almost every concurrency question hides one of three bugs. Name it first.

  • Race condition (lost update): two threads read the same value, both compute, and both write, so one write is lost. Two increments of a counter produce one.
  • Deadlock: two threads each hold a lock the other needs, and both wait forever. It happens when one thread transfers from account A to B while another transfers from B to A.
  • Visibility (stale read): one thread writes a field, and another keeps reading the old value from a register or cache. The classic case is a stop flag that the worker never sees.

Here is the lost update, one step at a time, on a counter that holds 5.

  • Thread A reads the counter and gets 5.
  • Thread B reads the counter and also gets 5.
  • Thread A writes 6.
  • Thread B writes 6.

There were two increments, and the value is 6: one increment is gone. The read-modify-write must be atomic, and each pattern below is a way to get there or to avoid the problem altogether.

Interview questions

  • What is a race condition? Show one and fix it.
  • Show a deadlock with two locks and fix it.
  • How do you size a thread pool, and what happens when it is full?
  • Design a bounded blocking queue from scratch.
  • What do volatile, synchronized and atomics guarantee in Java, and what does the GIL guarantee in Python?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio