Patterns and antipatterns question 150 of 180 junior
What is the producer/consumer pattern and what does the queue actually provide?
- A way to run tasks faster
- Correct: Decoupling of rate and of lifecycle: the queue is the only shared state, it provides the happens-before edge, and a bounded one provides backpressure
- A replacement for a thread pool
- A design that requires
wait/notify
Producers and consumers never touch each other's data; the only shared object is the queue, and
BlockingQueue handles the synchronisation, the blocking and the memory visibility (a put
happens-before the corresponding take). That reduces a concurrency problem to a data structure
choice.
The bound is the design decision. Bounded means a fast producer is slowed down by a slow consumer, which is backpressure, and the system degrades gracefully. Unbounded means the mismatch accumulates in memory until the process dies.
The poison pill is the idiomatic shutdown: put a sentinel per consumer so each one sees exactly one and exits, rather than interrupting mid-work. A thread pool is this pattern wearing a nicer API.
Quiz yourself on Patterns and antipatterns Suggest a correction