Thread-Safe Queue Design

A bounded blocking queue built from a lock and two condition variables, traced and tested with real threads; then the two-lock and lock-free designs behind Java's queues and the ABA problem.

Overview

A thread-safe queue is the part of a system where producers hand work to consumers: a thread pool's task queue, a log writer's buffer, the stage between a network reader and a parser. It has to do two things a plain queue does not. It must survive several threads pushing and popping at once, and it must make a consumer wait when there is nothing to take and a producer wait when there is no room.

The interview usually starts with the bounded blocking queue, because it exercises the exact skills a concurrency question tests: a lock, a condition variable, the loop around the wait, and a test with real threads. From there it goes to the designs behind library queues: one lock, two locks, or no lock at all.

What goes wrong without a lock

A single pop is several steps: read the head, read the item, move the head. Two consumers interleaving those steps can both take the same item, or one can move the head past an item nobody took. Here is one way it goes wrong on the queue [1, 2, 3].

  • Consumer A reads the head and sees item 1. The queue is still [1, 2, 3].
  • Consumer B reads the head and also sees item 1. The queue is still [1, 2, 3].
  • A takes item 1 and moves the head, leaving [2, 3].
  • B takes item 1 again and moves the head, leaving [3].

Both consumers got 1, and item 2 was never delivered.

The fix is to make the whole operation one indivisible step from every other thread's point of view. A lock does that by letting one thread at a time run the steps; a lock-free design does it with a single atomic compare-and-swap.

Interview questions

  • Implement a bounded blocking queue where producers block when it is full and consumers block when it is empty.
  • What is the ABA problem in lock-free data structures, and how is it avoided?
  • What is the difference between ArrayBlockingQueue and LinkedBlockingQueue in Java?
  • What should happen when the queue is full? Design the backpressure.
  • Design a work-stealing queue for a thread pool.

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio