Skip to the page

Concurrency in LLD · mid

Producer-consumer and blocking queues

A producer-consumer queue needs waiting and waking done right. Use a while loop around the wait condition, wake the right side, or better, use a ready-made blocking queue.

The notes

What you must know

  • In a hand-written queue, if must be while: after waking the condition may be false again (another consumer took the item first, or a spurious wakeup). Otherwise poll can return null and put can pass capacity.
  • notify wakes one arbitrary thread that may be of the same kind, and everyone can end up waiting. Use notifyAll, or a ReentrantLock with two conditions (notFull and notEmpty) and signal the right one.
  • Real code: ArrayBlockingQueue or LinkedBlockingQueue (put and take), Python queue.Queue. In Node.js use an async queue with a concurrency limit.
  • Do not poll with Thread.sleep. Wait on a condition.
  • Shutdown: a poison-pill item or interrupting consumers. Never swallow InterruptedException; keep or restore the interrupt flag.
  • Bound the queue. An unbounded queue eats memory.
  • The same idea appears in the logging library (async appender queue), the task scheduler and the pub-sub problem.

The red pen

Common traps: mistake → fix

  • Mistake: Adding volatile fixes the queue

    Fix: the problem is the wait condition, not visibility.

  • Mistake: Sleeping in a loop is a fine way to wait

    Fix: it wastes CPU and adds delay.

  • Mistake: Catching and ignoring InterruptedException is harmless

    Fix: it breaks shutdown.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the producer-consumer problem?
  2. Find the bugs in this hand-written blocking queue.
  3. Why while and not if around wait?
  4. How do you stop the consumers cleanly?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview