Producer-Consumer with BlockingQueue
MediumConcurrencyProducer-ConsumerBlockingQueueSemaphoreMutexThread Pool
Problem Statement
Design a multi-producer, multi-consumer system using a shared bounded buffer. Multiple producer threads generate integer items and push them onto the queue; multiple consumer threads pull items and process them. Implement the core SharedBuffer class from scratch without using Java's BlockingQueue.
class SharedBuffer {
private final int capacity;
public SharedBuffer(int capacity) { this.capacity = capacity; }
// Producer calls this
public void produce(int item) throws InterruptedException {}
// Consumer calls this
public int consume() throws InterruptedException {}
// Graceful shutdown
public void shutdown() {}
public boolean isShutdown() {}
}
Key Entities
- SharedBuffer: Central data structure with bounded capacity.
- Producer Thread: Generates data items and calls
produce(). - Consumer Thread: Fetches items via
consume()and processes them. - ReentrantLock + Conditions (notFull, notEmpty): Core synchronization.
Requirements
- Producers must block when the buffer is full.
- Consumers must block when the buffer is empty.
- Support
shutdown()to gracefully drain the queue and unblock waiting threads. - Support N producers and M consumers running concurrently.
- No item must be produced or consumed more than once.
Asked at: Amazon, Google, Microsoft, Uber, Flipkart, Paytm, Swiggy
!Constraints
- 1 ≤ capacity ≤ 10000
- Number of producer threads: 1–20
- Number of consumer threads: 1–20
- Items are non-negative integers.
- After shutdown(), blocked consumers drain remaining items then return sentinel value (-1).
Output
Run or submit your code to see output here.