KatInterview

Concurrent Queue with Bounded Capacity and Graceful Shutdown

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythreadingsynchronization

Last updated

Implement a thread-safe FIFO queue with fixed capacity, blocking operations, timeout support, and coordinated shutdown behavior.

You need to build a thread-safe queue that supports multiple producers and consumers working concurrently. The queue enforces a maximum size and blocks callers when full or empty.

Requirements

Implement a BoundedBlockingQueue class with these operations:

__init__(capacity: int)
Create a queue that holds at most capacity elements. Raise ValueError if capacity is not a positive integer.

put(item: Any, timeout: Optional[float] = None) -> None
Add item to the back of the queue. If the queue is full, block the caller until space opens up, the optional timeout (in seconds) elapses, or the queue shuts down. A None timeout means wait indefinitely.

take(timeout: Optional[float] = None) -> Any
Remove and return the front element. If the queue is empty, block until an element arrives, the optional timeout elapses, or the queue shuts down. A None timeout means wait indefinitely.

close() -> None
Initiate shutdown. All current and future put operations must raise QueueClosedError. Consumers calling take should still be able to retrieve any elements already in the queue; once drained, take raises QueueClosedError.

Define two custom exceptions:

  • QueueClosedError: raised when an operation cannot proceed because the queue is shut down
  • QueueTimeoutError: raised when a blocking operation times out before succeeding

Example

q = BoundedBlockingQueue(capacity=2)
q.put(10)
q.put(20)
# Queue is now full

q.take()  # returns 10
q.put(30)  # succeeds; queue now holds [20, 30]

q.close()
# q.put(40) would raise QueueClosedError
q.take()  # returns 20 (draining existing items)
q.take()  # returns 30
# q.take() now raises QueueClosedError

Constraints

  • Capacity is between 1 and 100,000
  • Multiple threads may call any method simultaneously
  • Handle spurious wakeups correctly
  • Treat timeout=0 as a non-blocking check
  • Treat negative timeout values as non-blocking (or raise ValueError)
  • Ensure no thread starvation or resource leaks when timeouts occur or during shutdown

Hints

Hint 1

Use a single lock with two condition variables: one for 'space available' and one for 'item available' to avoid waking all threads on every operation.

Hint 2

Compute an absolute deadline from the timeout once, then subtract elapsed time on each loop iteration to handle spurious wakeups correctly.

Hint 3

In the take loop, check for available items first, then check if closed; this ordering allows consumers to drain the queue after shutdown.