Design Data Structures · Pattern 9 of 10
Concurrency: a bounded blocking queue
Producers wait while the queue is full and consumers wait while it is empty. One lock protects the queue, and a condition variable lets a thread sleep until another one changes the state.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Several threads add and remove items
- A method must block (wait) until there is space or data
- Producer and consumer, or a fixed pool of slots
The template
class BoundedBlockingQueue {
private final Deque<Integer> q = new ArrayDeque<>();
private final int capacity;
BoundedBlockingQueue(int capacity) { this.capacity = capacity; }
synchronized void enqueue(int element) throws InterruptedException {
while (q.size() == capacity) wait(); // while, not if: re-check after waking
q.addLast(element);
notifyAll(); // wake threads waiting for an item
}
synchronized int dequeue() throws InterruptedException {
while (q.isEmpty()) wait();
int x = q.pollFirst();
notifyAll(); // wake threads waiting for space
return x;
}
synchronized int size() { return q.size(); }
} import threading
from collections import deque
class BoundedBlockingQueue:
def __init__(self, capacity):
self.capacity, self.q = capacity, deque()
self.cond = threading.Condition() # a lock plus wait / notify
def enqueue(self, element):
with self.cond:
while len(self.q) == self.capacity: # while, not if: re-check after waking
self.cond.wait()
self.q.append(element)
self.cond.notify_all() # wake threads waiting for an item
def dequeue(self):
with self.cond:
while not self.q:
self.cond.wait()
x = self.q.popleft()
self.cond.notify_all() # wake threads waiting for space
return x
def size(self):
with self.cond:
return len(self.q) class BoundedBlockingQueue {
deque<int> q;
int capacity;
mutex m;
condition_variable cv;
public:
BoundedBlockingQueue(int capacity) : capacity(capacity) {}
void enqueue(int element) {
unique_lock<mutex> lock(m);
cv.wait(lock, [&] { return (int)q.size() < capacity; }); // re-checks after every wake-up
q.push_back(element);
cv.notify_all(); // wake threads waiting for an item
}
int dequeue() {
unique_lock<mutex> lock(m);
cv.wait(lock, [&] { return !q.empty(); });
int x = q.front(); q.pop_front();
cv.notify_all(); // wake threads waiting for space
return x;
}
int size() { lock_guard<mutex> lock(m); return q.size(); }
}; // JavaScript runs one thread, so "blocking" means returning a promise that resolves later
class BoundedBlockingQueue {
constructor(capacity) { this.capacity = capacity; this.items = []; this.takers = []; this.putters = []; }
enqueue(x) {
if (this.takers.length) { this.takers.shift()(x); return Promise.resolve(); } // hand it straight over
if (this.items.length < this.capacity) { this.items.push(x); return Promise.resolve(); }
return new Promise((done) => this.putters.push(() => { this.items.push(x); done(); })); // wait for space
}
dequeue() {
if (!this.items.length) return new Promise((done) => this.takers.push(done)); // wait for an item
const x = this.items.shift();
if (this.putters.length) this.putters.shift()(); // space opened: let one producer in
return Promise.resolve(x);
}
size() { return this.items.length; }
} The variations
-
1Lock plus condition: wait while you cannot proceed
Take the lock, loop
while (cannot proceed) wait(), change the queue, then notify the others. Waiting releases the lock so another thread can make progress. Java can also use aReentrantLockwith two conditions (notFull, notEmpty), or two semaphores counting free and used slots.
Mistakes to avoid
- Waiting with
ifinstead ofwhile: a thread can wake up and find the condition false again (another thread got there first, or a spurious wake-up). - Calling
notify(one thread) when producers and consumers share one condition: it may wake the wrong kind and everyone sleeps. UsenotifyAll, or two separate conditions. - Reading
sizeor the queue without holding the lock.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.