Design a Thread-Safe Bounded Blocking Queue
Company: Latitudeai
Role: Backend Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Onsite
# Design a Thread-Safe Bounded Blocking Queue
Design a fixed-capacity FIFO queue shared by multiple producer and consumer threads. Provide operations equivalent to:
- `put(item)`: wait while the queue is full, then append the item.
- `take()`: wait while the queue is empty, then remove and return the oldest item.
- `close()`: reject future puts and allow consumers to drain already queued items; once drained, a take reports that the queue is closed.
Explain your classes, synchronization, state invariants, error semantics, and how callers can use timeouts or cancellation without corrupting the queue. Pseudocode is sufficient.
### Constraints & Assumptions
- Capacity is positive and does not change.
- Items may be arbitrary values, including values that should not be confused with a closed sentinel.
- Spurious wakeups and cancellation can occur.
- Correctness and a clear lock-based design matter more than a lock-free implementation.
### Clarifying Questions to Ask
- Should `put` and `take` support deadlines, cancellation tokens, or both?
- What exception or result represents a closed queue?
- Is strict fairness among waiting threads required?
- Must `close` itself wait for the queue to drain?
### What a Strong Answer Covers
- FIFO and capacity invariants protected by a well-defined synchronization boundary
- Condition waits in loops with correct full, empty, and closed predicates
- Atomic close behavior and wakeup of every affected waiter
- Timeout and cancellation paths that leave state unchanged
- Linearization points, contention trade-offs, and concurrency tests
### Follow-up Questions
- Why is checking the condition once before waiting incorrect?
- Which waiters must be notified after a put, take, or close?
- How would you reduce contention for very high throughput?
- What changes if one consumer crashes while processing an item?
Quick Answer: Design a thread-safe bounded blocking queue for multiple producers and consumers, with FIFO ordering and well-defined put, take, and close behavior. Discuss synchronization invariants, spurious wakeups, cancellation, timeouts, contention, and race-focused testing.