Design a Thread-Safe Bounded Blocking Queue

Medium
ConcurrencyProducer-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 available
  • dequeue() → item; blocks if queue is empty until an item is available
  • offer(item, timeout) → boolean; tries to enqueue within timeout, returns false if still full
  • poll(timeout) → item or null; tries to dequeue within timeout
  • size() → current number of elements
  • isEmpty(), isFull() → boolean checks
  • peek() → 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 Semaphore implementation
  • 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) → unlock
    • dequeue: 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.