A classic concurrency pattern where one or more producers create items and place them in a shared bounded buffer, while consumers remove and process them. The buffer acts as a decoupling mechanism.
Watch producers turn yellow (blocked) when the queue is full, and consumers block when empty. The bounded buffer maintains backpressure!
When the queue is FULL, producers must wait (block) until a consumer removes an item. This prevents memory overflow.
When the queue is EMPTY, consumers must wait (block) until a producer adds an item. This prevents busy-waiting.
Start simulation to see events...
// Bounded buffer with blocking
class BoundedQueue<T> {
private queue: T[] = [];
private maxSize: number;
async put(item: T) {
while (queue.length >= maxSize) {
await this.waitForSpace();
}
this.queue.push(item);
this.notifyConsumers();
}
async take(): Promise<T> {
while (queue.length === 0) {
await this.waitForItem();
}
const item = this.queue.shift()!;
this.notifyProducers();
return item;
}
}