Implement Blocking Queue using Semaphore
Filed under Salesforce
Free read 2 of 3Confirm if the queue should be FIFO and what the behavior is for multiple threads.
The question
Implement a thread-safe blocking queue that supports 'put' and 'take' operations using semaphores to manage capacity and synchronization.
Constraints
- Queue must have a fixed capacity.
- Put blocks when queue is full.
- Take blocks when queue is empty.
- Must be thread-safe.
Examples
- Input
- Capacity=2, ops: put(1), put(2), take()
- Output
- 1, 2, queue has 1 element
- Why
- The queue accepts two items, then take removes the first.
Approach
Confirm if the queue should be FIFO and what the behavior is for multiple threads.
Use one semaphore for empty slots (initialized to capacity) and one for filled slots (initialized to 0).
Use a Mutex/Lock to ensure exclusive access to the underlying collection during modification.
Consider thread interruption and potential starvation.
Tips
- What they are testing: Verify that multiple producer and consumer threads do not cause race conditions or deadlocks.
- Common mistake: Forgetting to use a mutex or lock to protect the internal data structure (e.g., deque) while using semaphores for signaling.
Related Salesforce questions
Collected from public candidate posts and coding forums. Updated Nov 2026.