LLD

Concurrency Patterns

Bounded Blocking Queue pattern

A queue with a fixed size, where put waits while it is full and take waits while it is empty. We write it three ways, with wait and notifyAll, with a lock and two conditions, and with two semaphores, and look at the bugs each way invites.

An office printer has a tray that holds a few jobs. When a laptop sends a job and the tray is full, the laptop's print dialog sits and waits. When the tray is empty, the printer sits idle until a job arrives. Nobody polls and nothing is lost: each side sleeps until the other side changes something.

A bounded blocking queue is that tray as a class. It has a fixed capacity, put waits while the queue is full, and take waits while it is empty. Java ships several, and the two most used are ArrayBlockingQueue and LinkedBlockingQueue. A thread pool or a logger with a background writer usually has one inside. As an interview question it fits on one line: implement put, take and size for a queue of fixed capacity that many threads use at once. The hard part is making threads wait and wake correctly.

In this article we write the print tray of an office print spooler. The first version has the two classic bugs: an if around the wait, and then a notify that wakes the wrong thread. Then we write it correctly three ways: with synchronized, wait and notifyAll, with a ReentrantLock and two Conditions, and with two Semaphores. At the end we compare them and say what to use in production.

All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the naive version, the rest from the finished design. Both programs run, and the outputs shown are what they print.

The queue we are building

Laptops in an office send print jobs to one printer through a tray. A job is a small record: an id, the laptop that sent it and a number of pages. The tray must:

  1. Hold at most a fixed number of jobs, set when it is built, and at least 1.
  2. put adds a job at the back. If the tray is full, it waits until there is room.
  3. take removes the job at the front. If the tray is empty, it waits until a job arrives.
  4. Keep jobs in order: first in, first out.
  5. size says how many jobs are waiting.
  6. Work with many laptops and many printers at once. No job is lost, none is taken twice, and the tray never holds more than its capacity.
  7. Let a waiting thread be interrupted. Its put or take throws InterruptedException and changes nothing.

There is no timeout and no shutdown in this list. Those belong to the design around the queue, and the Producer-Consumer pattern page builds them.

The tray and its two waits
The tray holds at most 3 jobs, here J1 at the front and J2 behind it, with one slot free. Laptops call put and the printer calls take. A laptop that finds the tray full waits in one line (left). A printer that finds it empty waits in the other (right). Each put or take may let a thread in the other line go on.The tray holds at most 3 jobs, here J1 at the front and J2 behind it, with one slot free. Laptops call put and the printer calls take. A laptop that finds the tray full waits in one line (left). A printer that finds it empty waits in the other (right). Each put or take may let a thread in the other line go on.
Laptops put jobs at the back; the printer takes them from the front. The tray holds at most 3 jobs, here J1 at the front and J2 behind it, with one slot free. Laptops call put and the printer calls take. A laptop that finds the tray full waits in one line (left). A printer that finds it empty waits in the other (right). Each put or take may let a thread in the other line go on.

This is the figure to draw first in an interview. It shows the two places where a thread can wait, and every later question is about who wakes whom. A thread in the left line can go on only after a take, and a thread in the right line only after a put.

The first version: wait inside an if

Java gives every object a lock and a waiting line. Inside synchronized (lock), a thread can call lock.wait(), which lets go of the lock and sleeps until another thread calls lock.notify() or lock.notifyAll(). The obvious queue uses that directly:

IfWaitQueue.javalines 12–34 of 47
    @Override    public void put(T item) throws InterruptedException {        Objects.requireNonNull(item, "item");        synchronized (lock) {            if (items.isFull()) {                lock.wait();            }            items.addLast(item);            lock.notifyAll();        }    }     @Override    public T take() throws InterruptedException {        synchronized (lock) {            if (items.isEmpty()) {                lock.wait();            }            T item = items.removeFirst();            lock.notifyAll();            return item;        }    }

Both methods hold lock, so only one thread at a time changes the ring. A laptop that finds the tray full calls wait(), and a take later calls notifyAll(), which wakes it. This version passes a test with one laptop and one printer.

It fails with two laptops. The program fills a tray of 2, starts two more laptops so both wait, and then takes one job:

$ java Main
-- 1. IfWaitQueue, capacity 2: two laptops wait for room
[2/2] laptop-C and laptop-D are waiting
[2/2] printer takes J1 (3 pages), and notifyAll wakes both laptops
[2/2] one laptop added its job; the other skipped the check and failed with
        java.lang.IllegalStateException: ring is full

-- 2. SingleNotifyQueue, capacity 1: 2 laptops and 2 printers, 20,000 jobs each
the run stalled: jobs are left, and every unfinished thread waits for a wake-up that never comes

Part 1 is the if bug, in four steps:

Why an if is not enough
1: The tray is full, so laptop-C and laptop-D both pass the if and call wait() (grey). 2: The printer takes J1, and notifyAll wakes both (amber). 3: laptop-C gets the lock first, adds J3, and its put returns (purple). The tray is full again. 4: laptop-D gets the lock next. It checked the if before it slept, so it goes straight to addLast and the ring refuses J4 (red).1: The tray is full, so laptop-C and laptop-D both pass the if and call wait() (grey). 2: The printer takes J1, and notifyAll wakes both (amber). 3: laptop-C gets the lock first, adds J3, and its put returns (purple). The tray is full again. 4: laptop-D gets the lock next. It checked the if before it slept, so it goes straight to addLast and the ring refuses J4 (red).
Two laptops wake for one free slot, and only one of them looks again. 1: The tray is full, so laptop-C and laptop-D both pass the if and call wait() (grey). 2: The printer takes J1, and notifyAll wakes both (amber). 3: laptop-C gets the lock first, adds J3, and its put returns (purple). The tray is full again. 4: laptop-D gets the lock next. It checked the if before it slept, so it goes straight to addLast and the ring refuses J4 (red).

A woken thread can lose the race. notifyAll wakes both laptops, but they take turns with the lock. By the time laptop-D runs, laptop-C has used the only free slot. Laptop-D checked the condition once, before it slept, and nothing makes it check again.

A thread can wake for no reason. Java allows wait() to return without any notify, which is called a spurious wake-up. A thread that trusts the if then writes into a full ring or reads from an empty one.

The damage depends on the ring. Our RingBuffer refuses to go past its capacity, so laptop-D gets an IllegalStateException for a mistake it did not make. A ring without that check would write J4 over J2, and J2 would never print. On the take side, when two printers wake for one job, the second gets NoSuchElementException.

The fix for both is the same: wrap each wait in a while. Part 2 of the output is the next bug, which we come to in Step 2. With a while but notify instead of notifyAll, the run stops with jobs left and every thread asleep.

The idea

A blocking queue is built from three parts:

  • One lock guards all the state: the items, their positions and the count. A thread checks and changes them only while it holds the lock.
  • A thread that cannot go on waits in a loop. It waits while the queue is full (or empty), and checks again every time it wakes. Waiting lets go of the lock, so other threads can change the state.
  • Each change wakes the threads it may help. A put may help a waiting take, and a take may help a waiting put.

Each thing a thread waits for, "not full" or "not empty", is a condition. Waiting in a loop until a condition holds is called Guarded Suspension. Java gives us three tools for the waiting part, and each version below uses one of them.

Building it, step by step

Step 1: where the jobs live

All three versions keep the jobs in the same RingBuffer, so they differ only in how threads wait:

queue/RingBuffer.javalines 9–41 of 58
final class RingBuffer<T> {    private final Object[] items;    private int head;    private int tail;    private int count;     RingBuffer(int capacity) {        if (capacity < 1) {            throw new IllegalArgumentException("capacity must be at least 1, was " + capacity);        }        items = new Object[capacity];    }     void addLast(T item) {        if (count == items.length) {            throw new IllegalStateException("ring is full");        }        items[tail] = item;        tail = (tail + 1) % items.length;        count++;    }     T removeFirst() {        if (count == 0) {            throw new NoSuchElementException("ring is empty");        }        @SuppressWarnings("unchecked")        T item = (T) items[head];        items[head] = null; // the ring must not keep a taken item alive        head = (head + 1) % items.length;        count--;        return item;    }

This is the same array-as-a-ring that the Producer-Consumer pattern page explains, with head and tail wrapping on lines 27 and 38. The new part is lines 23 and 32: the ring throws instead of going past full or empty. RingBuffer is package-private and not thread-safe, because each queue guards it with its own lock.

Decision

Where do the jobs live?

A linked list that grows

Each put allocates a node, and the list has no limit of its own, so the capacity check lives only in the queue. This is what LinkedBlockingQueue does. It is a good fit when the capacity is large and usually far from reached.

An ArrayDeque with a size check

The deque does the index work. It also works, but it can grow, so a missing capacity check fails silently instead of loudly.

A fixed array used as a ringOur pick

The array is allocated once and never grows. addLast throws if the ring is full, so a bug in any queue shows up as an exception instead of a lost job. The cost is one small class with two indexes to get right.

Step 2: synchronized, a while and notifyAll

MonitorQueue is the first version with the two fixes:

queue/MonitorQueue.javalines 14–43 of 49
    @Override    public void put(T item) throws InterruptedException {        Objects.requireNonNull(item, "item");        synchronized (lock) {            while (items.isFull()) {                lock.wait();            }            items.addLast(item);            lock.notifyAll();        }    }     @Override    public T take() throws InterruptedException {        synchronized (lock) {            while (items.isEmpty()) {                lock.wait();            }            T item = items.removeFirst();            lock.notifyAll();            return item;        }    }     @Override    public int size() {        synchronized (lock) {            return items.size();        }    }

Line 18 is a while. A laptop that wakes from line 19 checks isFull() again with the lock held. If another laptop took the slot first, or nothing woke it at all, it goes back to sleep. After the loop, the tray is certain to have room, because nothing can change it while this thread holds lock.

Line 22 wakes every waiting thread with notifyAll, and line 33 does the same after a take. The lock is a private object rather than this, so code outside the class cannot hold it, wait on it or wake its threads. size() takes the lock too (line 40), so it sees the count that the last put or take wrote.

Why not notify, which wakes only one thread? Java's built-in lock has a single waiting line. Laptops waiting for room and printers waiting for a job sleep in the same line, and notify picks any one of them. If it picks a thread from the wrong side, that thread finds nothing to do and sleeps again, and the thread that could have gone on is not woken by this change:

notify wakes the wrong side
A tray of 1, and laptop-A sends only one job. 1: Both printers wait on an empty tray. 2: laptop-A puts J1, and notify wakes printer-1, which must get the lock back before it runs. 3: laptop-B gets the lock first, finds the tray full and waits. 4: printer-1 takes J1, and notify wakes printer-2 (amber), not laptop-B. 5: printer-2 finds the tray empty and waits again. 6: printer-1 asks for the next job and waits too. The tray has room and laptop-B has a job, but all three threads wait, and none will notify (red).A tray of 1, and laptop-A sends only one job. 1: Both printers wait on an empty tray. 2: laptop-A puts J1, and notify wakes printer-1, which must get the lock back before it runs. 3: laptop-B gets the lock first, finds the tray full and waits. 4: printer-1 takes J1, and notify wakes printer-2 (amber), not laptop-B. 5: printer-2 finds the tray empty and waits again. 6: printer-1 asks for the next job and waits too. The tray has room and laptop-B has a job, but all three threads wait, and none will notify (red).
With one waiting line, a wake-up meant for a laptop can go to a printer. A tray of 1, and laptop-A sends only one job. 1: Both printers wait on an empty tray. 2: laptop-A puts J1, and notify wakes printer-1, which must get the lock back before it runs. 3: laptop-B gets the lock first, finds the tray full and waits. 4: printer-1 takes J1, and notify wakes printer-2 (amber), not laptop-B. 5: printer-2 finds the tray empty and waits again. 6: printer-1 asks for the next job and waits too. The tray has room and laptop-B has a job, but all three threads wait, and none will notify (red).

Part 2 of the first program's output shows this happening: two laptops and two printers share a tray of 1 through SingleNotifyQueue, which has the while but calls notify. Every run stalled with jobs left. Nothing throws and nothing is logged. The threads wait for ever.

Decision

Which threads does a change wake?

notify: one thread

This wakes the fewest threads. It is safe only when every waiting thread waits for the same thing, so any one of them can use the change. Here laptops and printers share one line, and the stall above is the result.

notifyAll: every waiting threadOur pick

Every thread wakes, checks its own while, and the one that can go on does. The cost is wasted wake-ups: with ten laptops waiting, a take frees one slot and wakes all ten, and nine go back to sleep after taking the lock in turn. Step 3 removes that cost.

Step 3: one lock, two conditions

A ReentrantLock can hand out any number of conditions, and each condition is its own waiting line. ConditionQueue gives laptops one line and printers the other:

queue/ConditionQueue.javalines 8–46 of 62
public final class ConditionQueue<T> implements BoundedBlockingQueue<T> {    private final RingBuffer<T> items;    private final ReentrantLock lock = new ReentrantLock();    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();     public ConditionQueue(int capacity) {        this.items = new RingBuffer<>(capacity);    }     @Override    public void put(T item) throws InterruptedException {        Objects.requireNonNull(item, "item");        lock.lockInterruptibly();        try {            while (items.isFull()) {                notFull.await();            }            items.addLast(item);            notEmpty.signal();        } finally {            lock.unlock();        }    }     @Override    public T take() throws InterruptedException {        lock.lockInterruptibly();        try {            while (items.isEmpty()) {                notEmpty.await();            }            T item = items.removeFirst();            notFull.signal();            return item;        } finally {            lock.unlock();        }    }

Laptops wait on notFull (line 24) and printers on notEmpty (line 38). await lets go of the lock and sleeps, exactly as wait does, and the while is still needed for the same two reasons. Each try ends in finally { lock.unlock(); }, because a ReentrantLock is not released when an exception leaves the block, unlike synchronized.

Here signal, which wakes one thread, is safe. A put adds exactly one job, so it can help exactly one printer, and line 27 wakes one thread from the printers' line. Only printers are in that line, so the woken thread is never a laptop. Line 41 does the same for laptops after a take. If a woken thread loses the race to a thread that has just arrived, the newcomer uses the job or the slot, and the woken one checks its while and waits again. Nothing is lost.

Neither the lock nor the conditions promise which waiting thread goes first. First in, first out applies to the jobs, not to the threads waiting to put them, so one laptop can be passed over many times. new ReentrantLock(true), new Semaphore(n, true) and new ArrayBlockingQueue<>(n, true) serve the thread that has waited longest, while synchronized has no fair mode. The fair versions cost throughput, because no newcomer may take a free lock.

Decision

One lock, or one lock for each end?

One lock for both endsOur pick

Put and take never run at the same time, even though they touch different ends of the ring. The design is easy to check. This is how ArrayBlockingQueue is built. The cost is that laptops and printers queue for the same lock.

A put lock and a take lock

Laptops and printers no longer block each other, which helps when both sides are busy. But the count becomes an AtomicInteger, a put that fills the first slot must take the take lock to signal a printer, and the storage must let both ends move at once, which suits a linked list. LinkedBlockingQueue is built this way.

Step 4: two semaphores

A semaphore holds a number of permits. acquire takes one, waiting while there are none, and release gives one back and wakes a waiting thread. SemaphoreQueue counts the free slots and the waiting jobs with two of them:

queue/SemaphoreQueue.javalines 10–40 of 53
public final class SemaphoreQueue<T> implements BoundedBlockingQueue<T> {    private final RingBuffer<T> items;    private final Semaphore freeSlots;    private final Semaphore waitingItems = new Semaphore(0);    private final Object lock = new Object();     public SemaphoreQueue(int capacity) {        this.items = new RingBuffer<>(capacity);        this.freeSlots = new Semaphore(capacity);    }     @Override    public void put(T item) throws InterruptedException {        Objects.requireNonNull(item, "item");        freeSlots.acquire();        synchronized (lock) {            items.addLast(item);        }        waitingItems.release();    }     @Override    public T take() throws InterruptedException {        waitingItems.acquire();        T item;        synchronized (lock) {            item = items.removeFirst();        }        freeSlots.release();        return item;    }

freeSlots starts at the capacity (line 18) and waitingItems at 0. A put takes a free slot on line 24, adds the job under the lock, and announces one more waiting job on line 28. A take does the reverse. There is no while here, because the semaphore does the counting: a laptop that gets a permit is certain to find room. The plain lock around the ring is still needed, because two laptops can hold permits at the same time and both reach addLast.

The trap is the order. A laptop must wait for its permit before it takes the lock. If it takes the lock first, this happens:

Sketchnot part of the final code
public void put(T item) throws InterruptedException {    synchronized (lock) {        freeSlots.acquire();     // the tray is full: waits here, still holding lock        items.addLast(item);    }    waitingItems.release();}

A laptop finds the tray full and waits on freeSlots while it holds lock. The printer gets a permit from waitingItems and then needs lock to remove a job. It can never get it, so it never releases a slot, and the laptop never wakes. That is a deadlock. wait and await let go of the one lock they belong to. acquire belongs to no lock, so it lets go of nothing.

Decision

Which comes first in put, the permit or the lock?

The lock, then the permit

It looks tidy, because everything happens inside one block. It deadlocks as soon as the tray is full and a laptop waits, as the sketch shows.

The permit, then the lockOur pick

The thread holds the lock only for the few lines that touch the ring, never while it waits. The signal (release) also comes after the lock is let go. The cost is that the ring and the permits can briefly disagree. A take that has removed a job but not yet called freeSlots.release() leaves size() below the capacity while a new put still waits.

Step 5: what an interrupt does

A thread waiting in put or take may be interrupted, for example by a shutdown. All three tools respond the same way: wait, await and acquire throw InterruptedException. In all three versions the exception leaves before the thread has changed anything. The monitor and condition versions are still inside their while and have not touched the ring. The semaphore version has not got its permit, so there is nothing to give back. The ConditionQueue takes its lock with lockInterruptibly(), so an interrupt while waiting for the lock itself also counts.

The demo below interrupts a laptop that waits on a full tray, and its job is never added. ConditionQueue and SemaphoreQueue also throw when the thread was interrupted before it called put, while MonitorQueue throws only once it has to wait.

Decision

What does a waiting thread do when it is interrupted?

Catch it and keep waiting

The queue looks friendlier, but a thread stuck on a full tray can then never be stopped, and whoever interrupted it waits for ever too.

Return null or false

The caller must check every result, and the interrupt is lost unless the queue sets the flag again.

Throw InterruptedException and change nothingOur pick

The caller learns at once, and the queue is exactly as it was. This is what Java's own BlockingQueue does, so callers already know how to handle it. The cost is a checked exception on put and take.

Step 6: one interface, three versions, many threads

All three classes implement BoundedBlockingQueue<T>, and the enum QueueKind builds any of them:

queue/QueueKind.javalines 3–16 of 16
/** The three versions on this page, so a caller can pick one by name. */public enum QueueKind {    MONITOR,    CONDITIONS,    SEMAPHORES;     public <T> BoundedBlockingQueue<T> create(int capacity) {        return switch (this) {            case MONITOR -> new MonitorQueue<>(capacity);            case CONDITIONS -> new ConditionQueue<>(capacity);            case SEMAPHORES -> new SemaphoreQueue<>(capacity);        };    }}

demo/RaceCheck.java runs four laptops, each putting 25,000 jobs, through a tray of 4 to three printers, on each version:

$ java demo.RaceCheck
4 laptops put 25000 jobs each through a tray of 4 to 3 printers
MONITOR     taken once: 100000  more than once: 0  never: 0  in order per laptop: true
CONDITIONS  taken once: 100000  more than once: 0  never: 0  in order per laptop: true
SEMAPHORES  taken once: 100000  more than once: 0  never: 0  in order per laptop: true

Every job was taken exactly once, and each printer saw any one laptop's jobs in the order that laptop sent them. In a scratch copy without the lock around the ring in SemaphoreQueue, two threads changed count and the indexes at the same time. In every run, threads died on exceptions from the ring, such as ring is full and ring is empty, or took a null job, and thousands of jobs were never taken.

The finished design

The finished design
MonitorQueue, ConditionQueue and SemaphoreQueue implement BoundedBlockingQueue. Each owns a RingBuffer and lists its own lock and waiting lines: a private Object, a ReentrantLock with two Conditions, or two Semaphores and an Object. QueueKind creates any of the three. PrintJob is the record the demo puts in the tray.MonitorQueue, ConditionQueue and SemaphoreQueue implement BoundedBlockingQueue. Each owns a RingBuffer and lists its own lock and waiting lines: a private Object, a ReentrantLock with two Conditions, or two Semaphores and an Object. QueueKind creates any of the three. PrintJob is the record the demo puts in the tray.
Three classes behind one interface, each owning a RingBuffer and guarding it its own way. MonitorQueue, ConditionQueue and SemaphoreQueue implement BoundedBlockingQueue. Each owns a RingBuffer and lists its own lock and waiting lines: a private Object, a ReentrantLock with two Conditions, or two Semaphores and an Object. QueueKind creates any of the three. PrintJob is the record the demo puts in the tray.

Here is one put on a full tray, through ConditionQueue:

One put on a full tray, traced
laptop-C calls put(J3) on a full tray (1). It takes the lock, finds the tray full and awaits notFull, which lets go of the lock (2, grey). The printer calls take (3), removes J1 and signals notFull (4, amber). take unlocks and returns J1 (5). laptop-C wakes, gets the lock back, finds room in the while and adds J3 (6). It signals notEmpty and unlocks (7), and put returns.laptop-C calls put(J3) on a full tray (1). It takes the lock, finds the tray full and awaits notFull, which lets go of the lock (2, grey). The printer calls take (3), removes J1 and signals notFull (4, amber). take unlocks and returns J1 (5). laptop-C wakes, gets the lock back, finds room in the while and adds J3 (6). It signals notEmpty and unlocks (7), and put returns.
The laptop sleeps without the lock, a take wakes it, and it checks again before adding. laptop-C calls put(J3) on a full tray (1). It takes the lock, finds the tray full and awaits notFull, which lets go of the lock (2, grey). The printer calls take (3), removes J1 and signals notFull (4, amber). take unlocks and returns J1 (5). laptop-C wakes, gets the lock back, finds room in the while and adds J3 (6). It signals notEmpty and unlocks (7), and put returns.

The whole project is below. Click any class name in the code to open that class.

queueConditionQueue.java
package queue; import java.util.Objects;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock; /** Version 2: one ReentrantLock with two conditions, one for each side. */public final class ConditionQueue<T> implements BoundedBlockingQueue<T> {    private final RingBuffer<T> items;    private final ReentrantLock lock = new ReentrantLock();    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();     public ConditionQueue(int capacity) {        this.items = new RingBuffer<>(capacity);    }     @Override    public void put(T item) throws InterruptedException {        Objects.requireNonNull(item, "item");        lock.lockInterruptibly();        try {            while (items.isFull()) {                notFull.await();            }            items.addLast(item);            notEmpty.signal();        } finally {            lock.unlock();        }    }     @Override    public T take() throws InterruptedException {        lock.lockInterruptibly();        try {            while (items.isEmpty()) {                notEmpty.await();            }            T item = items.removeFirst();            notFull.signal();            return item;        } finally {            lock.unlock();        }    }     @Override    public int size() {        lock.lock();        try {            return items.size();        } finally {            lock.unlock();        }    }     @Override    public int capacity() {        return items.capacity();    }}
Click a class name in the code to open its fileJava · 62 lines · 543 in the project

demo/Main.java runs the same steps on a tray of 2 for each version. Each line starts with the tray's size before that step:

$ java demo.Main
The print tray as a MONITOR queue, capacity 2
-- 1. put waits while the tray is full
[0/2] laptop-A submits J1 (3 pages)
[1/2] laptop-B submits J2 (1 page)
[2/2] laptop-C submits J3 (2 pages): waits, the tray is full
[2/2] printer takes J1 (3 pages)
        laptop-C's put returns, and J3 is at the back
[2/2] printer takes J2 (1 page)
[1/2] printer takes J3 (2 pages)
-- 2. take waits while the tray is empty
[0/2] printer asks for a job: waits, the tray is empty
[0/2] laptop-A submits J4 (5 pages)
        printer's take returns J4 (5 pages)
-- 3. an interrupted put adds nothing
[0/2] laptop-B submits J5 (1 page)
[1/2] laptop-B submits J6 (4 pages)
[2/2] laptop-C submits J7 (2 pages): waits, the tray is full
        laptop-C is interrupted: put throws InterruptedException
[2/2] printer takes J5 (1 page)
[1/2] printer takes J6 (4 pages)
[0/2] J7 was never added

The same steps on a CONDITIONS queue: the same trace
The same steps on a SEMAPHORES queue: the same trace

Part 1 covers requirements 2 and 4. J1 and J2 fill the tray, so laptop-C's put waits. When the printer takes J1, laptop-C's put returns and J3 goes in behind J2, and the jobs come out as J1, J2, J3. In part 2 the printer asks for a job on an empty tray and waits (requirement 3), and laptop-A's J4 goes straight to it. Part 3 is requirement 7: laptop-C is interrupted while waiting with J7, its put throws, and the tray still holds only J5 and J6. The last two lines say the other two versions printed exactly the same trace.

What it costs

The three versions behave the same from outside. They differ in how much they wake and how easy they are to get wrong:

MonitorQueueConditionQueueSemaphoreQueue
Waits withwait in a whileawait in a whileacquire, no loop
Waiting linesOne for both sidesOne per sideOne per semaphore
A change wakesEvery waiting threadOne thread of the side it helpsOne thread of the side it helps
UnlockingAutomaticfinally on every pathAutomatic, short blocks
The easy mistakenotify instead of notifyAllForgetting unlock, signalling the wrong conditionThe lock before the permit
Fits whenFew threads waitMany threads wait on both sidesThe limit is a count of permits
What each version wakes
Five laptops wait on a full tray, and a printer takes a job. MonitorQueue's notifyAll wakes all five (amber), and four find the tray full again and go back to sleep (red text). ConditionQueue's notFull.signal() and SemaphoreQueue's freeSlots.release() each wake one laptop, and the rest stay asleep (grey).Five laptops wait on a full tray, and a printer takes a job. MonitorQueue's notifyAll wakes all five (amber), and four find the tray full again and go back to sleep (red text). ConditionQueue's notFull.signal() and SemaphoreQueue's freeSlots.release() each wake one laptop, and the rest stay asleep (grey).
notifyAll wakes everyone; a condition or a semaphore wakes one thread of the right side. Five laptops wait on a full tray, and a printer takes a job. MonitorQueue's notifyAll wakes all five (amber), and four find the tray full again and go back to sleep (red text). ConditionQueue's notFull.signal() and SemaphoreQueue's freeSlots.release() each wake one laptop, and the rest stay asleep (grey).

notifyAll costs wake-ups. Each woken thread must take the lock in turn just to find out it cannot go on. With a few threads this does not matter. With hundreds waiting, every put and take wakes all of them.

Conditions cost discipline. The lock does not release itself, and each signal must go to the right condition. If put signals notFull instead of notEmpty, the code compiles, and a waiting printer is never woken by a put.

Semaphores split one fact in two. The permits and the ring can briefly disagree, so size() can show room while a put still waits for a permit. The order of the lock and the permit is easy to get wrong.

Every version holds the lock for every put and take. Many threads on many cores queue for that one lock. Two locks, as in LinkedBlockingQueue, or a queue without locks, help only when this shows up in a measurement.

What to use in production

Our three versions are for understanding and for interviews. In production, use the queues Java already has, which are tested far more than ours:

Sketchnot part of the final code
BlockingQueue<PrintJob> tray = new ArrayBlockingQueue<>(50);         // one lock, two conditions, an arrayBlockingQueue<PrintJob> spool = new LinkedBlockingQueue<>(10_000);   // a put lock and a take lock, linked nodes tray.put(job);                                         // waits while fullPrintJob next = tray.take();                           // waits while emptyboolean added = tray.offer(job, 2, TimeUnit.SECONDS);  // waits at most 2 seconds

ArrayBlockingQueue is built like our ConditionQueue. LinkedBlockingQueue is the two-lock design from Step 3. If you leave out its capacity, the capacity is Integer.MAX_VALUE, so in practice put never waits. Both also offer offer and poll with a timeout, which a real caller usually needs so that a stuck printer does not hold a laptop for ever.

Bounded Blocking Queue or Producer-Consumer?

The two are often named together, because one is a part of the other:

Bounded Blocking QueueProducer-Consumer
What it isOne class: a queue whose put and take waitA design: threads that make work, threads that do it, and a buffer between them
What it decidesHow threads wait and wakeWhat a producer is told when the buffer is full, how consumers stop, what a crash loses
Typical interfaceput, take, sizeoffer with a timeout, take, close, workers that start and stop
ExampleThis page's print trayPayment callbacks settled by workers

The Producer-Consumer pattern page writes its own buffer with a close and an offer that gives up after a short wait, because its service needs both. This page is the inside of that buffer.

A short way to say it: a bounded blocking queue is the buffer, and Producer-Consumer is the design that puts threads on both sides of it.

In an interview

The question can arrive as it is: implement a bounded blocking queue with put, take and size. It also sits inside a thread pool, a logger with a background writer, a rate limiter that hands out permits, and any Producer-Consumer question.

A good order for presenting it:

  1. State the contract. Say that the queue has a fixed capacity, that put waits while it is full and take while it is empty, that jobs leave in order, and what an interrupt does.
  2. Draw the two waiting lines. Say which change wakes which line.
  3. Write the lock-and-two-conditions version, with a while around each await and unlock in a finally.
  4. Explain why not if and why not a single notify, with the lost race and the wrong-side wake-up.
  5. Mention the alternatives. synchronized with notifyAll is shorter, and semaphores need the permit before the lock. In production, ArrayBlockingQueue does all of this.

Common mistakes:

  • An if around the wait. A thread that lost the race, or woke for no reason, writes into a full queue or reads from an empty one.
  • A single notify with one waiting line. It can wake a thread of the wrong side while the thread that could go on sleeps. Once every thread waits like this, the queue stalls.
  • Calling wait or notify without holding that object's lock. Java throws IllegalMonitorStateException.
  • Forgetting unlock on an exception path. The next thread waits for the lock for ever.
  • Taking the lock before the semaphore permit. The waiting thread keeps the lock that the other side needs to free a permit.
  • Busy-waiting in a loop on size(). It burns a core, and checking for room and adding are still two separate steps that another thread can get between.

Summary

  • A bounded blocking queue has a fixed capacity: put waits while it is full, and take waits while it is empty.
  • One lock guards the items and the count, and every wait sits in a while that checks again after waking.
  • With synchronized, both sides share one waiting line, so the queue wakes everyone with notifyAll. A single notify can wake the wrong side and stall.
  • With a ReentrantLock, two conditions give each side its own line, so signal wakes one thread of the side the change helps.
  • With semaphores, the permits do the counting, and a thread must get its permit before it takes the lock.
  • In production, use ArrayBlockingQueue or LinkedBlockingQueue, and build Producer-Consumer on top of one.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.