Concurrent Queue with Bounded Capacity and Graceful Shutdown
Data Structure DesignModel answerLast 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 downQueueTimeoutError: 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=0as 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem demonstrates the monitor pattern: shared mutable state protected by a lock, with condition variables for coordination.
Core Structure
All queue state lives behind a single mutex:
- A
dequeholding the items in FIFO order - The fixed capacity
- A boolean flag tracking whether the queue is closed
Two condition variables share that mutex:
not_full: producers wait here when the queue reaches capacitynot_empty: consumers wait here when the queue is empty
Using separate conditions is more efficient than a single condition with notify_all(). Each put wakes exactly one waiting consumer; each take wakes exactly one waiting producer. With one condition, every operation would wake every thread.
Wait Loop Pattern
Both put and take follow the same structure:
- Acquire the lock
- Loop:
- Check termination conditions (closed state)
- Check success condition (space available / item available)
- If neither applies, wait on the appropriate condition variable
- Re-check after waking up
- Perform the operation and notify the complementary condition
The while loop (not if) is critical. Python's condition variables can experience spurious wakeups—wait() returns without a signal. Additionally, another thread may "barge" in after a notify and consume the state change before the woken thread acquires the lock. The loop handles both cases by rechecking the predicate.
Timeout Handling
We compute an absolute deadline using time.monotonic() once at the start. Each wait iteration uses only the remaining time until that deadline.
If we used a fixed duration on each wait, a spuriously woken thread would restart its full timeout, potentially blocking forever. Using a monotonic clock prevents wall-clock adjustments (NTP, daylight saving) from affecting timeouts.
Before raising QueueTimeoutError, we recheck the predicate. This handles races: if a notify arrives just as our timeout expires, we loop, see the new item or free slot, and succeed.
Shutdown Semantics
The order of checks encodes the shutdown behavior:
In put:
- If closed → raise immediately
- If space available → insert
- Otherwise → wait
Checking closed first means producers are rejected even when space exists.
In take:
- If items available → return (even if closed)
- If closed and empty → raise
- Otherwise → wait
Checking for items first allows consumers to drain the queue after shutdown.
When close() is called:
- Set the
closedflag - Call
notify_all()on both conditions to wake every waiting thread - Blocked producers wake, see
closed, and raise - Blocked consumers either find a remaining item or find the queue empty and raise
Edge Cases
- Invalid capacity: Reject capacity < 1, non-integers, and
bool(which passesisinstance(x, int)in Python) timeout=0: Non-blocking check; succeed immediately or raiseQueueTimeoutError- Negative timeout: Clamp to 0 and treat as non-blocking
timeout=None: Block indefinitely until success or shutdown- Repeated
close(): Second call is a no-op Noneas an item: Valid; the design never uses sentinels
Complexity
- Time:
putandtakeare O(1) amortized (deque operations), plus blocking time.closeis O(W) where W is the number of waiting threads due tonotify_all. - Space: O(capacity) for the buffer, plus O(W) for waiter records in the condition variables.
Implementation
import threading
import time
from collections import deque
from typing import Any, Optional
class QueueClosedError(Exception):
pass
class QueueTimeoutError(Exception):
pass
class BoundedBlockingQueue:
def __init__(self, capacity: int):
if isinstance(capacity, bool) or not isinstance(capacity, int) or capacity < 1:
raise ValueError("capacity must be a positive integer")
self._capacity = capacity
self._items: deque = deque()
self._closed = False
self._lock = threading.Lock()
self._not_full = threading.Condition(self._lock)
self._not_empty = threading.Condition(self._lock)
@staticmethod
def _compute_deadline(timeout: Optional[float]) -> Optional[float]:
if timeout is None:
return None
return time.monotonic() + max(0.0, timeout)
@staticmethod
def _wait_until(cond: threading.Condition, deadline: Optional[float]) -> None:
if deadline is None:
cond.wait()
return
remaining = deadline - time.monotonic()
if remaining <= 0:
raise QueueTimeoutError("operation timed out")
cond.wait(timeout=remaining)
def put(self, item: Any, timeout: Optional[float] = None) -> None:
deadline = self._compute_deadline(timeout)
with self._lock:
while True:
if self._closed:
raise QueueClosedError("cannot put to closed queue")
if len(self._items) < self._capacity:
self._items.append(item)
self._not_empty.notify()
return
self._wait_until(self._not_full, deadline)
def take(self, timeout: Optional[float] = None) -> Any:
deadline = self._compute_deadline(timeout)
with self._lock:
while True:
if self._items:
item = self._items.popleft()
self._not_full.notify()
return item
if self._closed:
raise QueueClosedError("queue is closed and empty")
self._wait_until(self._not_empty, deadline)
def close(self) -> None:
with self._lock:
if self._closed:
return
self._closed = True
self._not_full.notify_all()
self._not_empty.notify_all()
Common Mistakes
- Using
ifinstead ofwhilearound waits, failing to handle spurious wakeups and barging - Reusing the same timeout duration on each wait iteration instead of computing remaining time
- Using
time.time()instead oftime.monotonic(), making timeouts vulnerable to clock adjustments - Notifying the wrong condition or using a single condition with excessive
notify_all()calls - Incorrect shutdown semantics: blocking consumers from draining, or allowing producers to continue
- Not validating that
boolvalues (which are integers in Python) are rejected for capacity