Design a Thread-Safe Bounded Blocking Queue
MediumConcurrencyProducer-ConsumerBlocking QueueSemaphoreCondition VariablesConcurrency
Problem Statement
Design a thread-safe bounded blocking queue that supports the classic producer-consumer pattern — producers block when queue is full and consumers block when queue is empty, with configurable capacity.
Requirements
Functional Requirements
enqueue(item)— add item; blocks if queue is full until space is availabledequeue()→ item; blocks if queue is empty until an item is availableoffer(item, timeout)→ boolean; tries to enqueue within timeout, returns false if still fullpoll(timeout)→ item or null; tries to dequeue within timeoutsize()→ current number of elementsisEmpty(),isFull()→ boolean checkspeek()→ view head without removing- Supports N concurrent producers and M concurrent consumers safely
Non-Functional Requirements
- Implemented using
ReentrantLock + Condition(notFull, notEmpty) - Alternatively demonstrate with
Semaphoreimplementation - No busy-waiting
- Fixed capacity set at construction time
Key Entities
- BoundedBlockingQueue<T>: capacity, items (array/LinkedList), lock (ReentrantLock), notFull (Condition), notEmpty (Condition), count
enqueue: lock → while(full) await(notFull) → add → signal(notEmpty) → unlockdequeue: lock → while(empty) await(notEmpty) → remove → signal(notFull) → unlock
Constraints
- Capacity >= 1
- No busy-waiting — use condition variables
- Deadlock-free: always release lock in finally block
- FIFO ordering: first enqueued item is first dequeued
!Constraints
- Capacity fixed at construction time, minimum 1
- No busy-waiting — blocking implemented via Condition.await()
- FIFO ordering guaranteed
- Lock released in finally block — deadlock prevention
- Spurious wake-up handled with while loop (not if)
Output
Run or submit your code to see output here.