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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What is the producer-consumer problem?
- Find the bugs in this hand-written blocking queue.
- Why while and not if around wait?
- How do you stop the consumers cleanly?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.