LLD

Concurrency Patterns

Producer-Consumer pattern

When work has to be accepted faster than it can be done, put it in a bounded buffer and let other threads do it. We build a UPI payment callback service twice, once settling each payment before answering the bank and once handing it to workers through a buffer.

At a busy restaurant, the person at the counter takes your order, writes a ticket and clips it to a rail. The cooks take tickets from the rail at their own pace. When the rail is full, the counter asks the next customer to wait a minute. At closing time, the counter stops taking orders, and the cooks finish every ticket already on the rail before they leave.

Software has the same shape wherever one part receives work quickly and another part does it slowly. A logger hands lines to a writer thread, and a crawler's fetchers hand pages to its parsers.

The Producer-Consumer pattern puts a buffer between the threads that receive the work and the threads that do it. In this article we build a service for UPI (Unified Payments Interface) payment callbacks twice. The first version settles each payment before it answers the bank. The second hands each payment to worker threads through a bounded buffer. Then we look at what the buffer costs and how the pattern differs from Observer and a thread pool.

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

The service we are building

When a customer pays for an order by UPI, the bank calls our service with a payment callback: payment P1 of $150 for order 8841 went through. Settling it means three things: mark the order paid, write a line in the ledger, and send the customer a receipt by text message (SMS). The ledger and the SMS gateway are outside our code. In this article we assume the bank waits up to 1 second for our answer, and sends the callback again later if it gets none or gets an error.

The service must:

  1. Answer the bank quickly, without waiting for the ledger or the SMS gateway.
  2. Settle every accepted delivery once. A 200 OK means "accepted".
  3. Hold at most a fixed number of callbacks waiting to be settled, however fast they arrive.
  4. When that many are waiting, wait a short, bounded time for room, then answer "busy" so the bank sends the callback again.
  5. Let several server threads accept callbacks and several workers settle them at the same time.
  6. Keep a callback whose settling fails, with the reason, and go on to the next one.
  7. On shutdown, stop accepting and answer "shutting down", not "busy", and settle everything already accepted before the workers stop.
Producers, a buffer and consumers
Server threads (the producers) offer each callback to a buffer of fixed size and answer the bank at once. Workers (the consumers) take callbacks from the front of the buffer and settle them. An offer has three outcomes: accepted, full after a short wait, or closed. A worker that finds the buffer empty waits, and one that finds it closed and empty stops.Server threads (the producers) offer each callback to a buffer of fixed size and answer the bank at once. Workers (the consumers) take callbacks from the front of the buffer and settle them. An offer has three outcomes: accepted, full after a short wait, or closed. A worker that finds the buffer empty waits, and one that finds it closed and empty stops.
Server threads put callbacks in; workers take them out; the buffer has a fixed size. Server threads (the producers) offer each callback to a buffer of fixed size and answer the bank at once. Workers (the consumers) take callbacks from the front of the buffer and settle them. An offer has three outcomes: accepted, full after a short wait, or closed. A worker that finds the buffer empty waits, and one that finds it closed and empty stops.

This is the figure to draw first in an interview. It names the three places where the design must decide something: what a producer does when the buffer is full, what a consumer does when it is empty, and how both sides learn that the service is shutting down.

The first version: settle, then answer

The obvious endpoint does the work and then answers:

CallbackEndpoint.javalines 13–19 of 20
    /** Runs on a web server thread for each callback the bank sends. */    public String receive(PaymentCallback callback) {        Objects.requireNonNull(callback, "callback");        ledger.record(callback);        sms.sendReceipt(callback);        return "200 OK";    }

This code is correct, and it is fine while the ledger and the SMS gateway are quick and reliable. The program runs it on a pretend clock, where the ledger takes 40 ms and the SMS gateway 300 ms:

$ java Main
1. A normal day: the ledger takes 40 ms and the SMS gateway 300 ms
   bank -> P1: 200 OK after 340 ms

2. The SMS gateway slows to 3,000 ms, and the bank waits at most 1,000 ms
   bank -> P2: 200 OK after 3,040 ms, but the bank stopped waiting at 1,000 ms
   bank -> P2 again: 200 OK after 3,040 ms, but the bank stopped waiting at 1,000 ms
   bank -> P2 again: 200 OK after 3,040 ms, but the bank stopped waiting at 1,000 ms
   P2: ledger lines 3, receipts sent 3

The bank waits for our slowest step. P1 is answered after 340 ms, and almost all of that is the SMS. The bank only needed to know that we have the callback.

A slow gateway turns into repeated work. When the SMS gateway slows to 3,000 ms, every answer comes after the bank has stopped waiting. The bank sends P2 again, and our code settles it again. P2 ends with three ledger lines and three receipts. A check on the payment id would stop the repeated work, but the bank would still send P2 three times.

Server threads end up waiting on the gateway. While the gateway is slow, each callback holds a thread for 3 seconds. A server with a fixed number of threads runs out during a burst, and its other requests wait too. Virtual threads make threads cheap, but each callback still misses the bank's 1 second and still adds load to a slow gateway.

Settling before answering
On the left, P1 on a normal day: the ledger takes 40 ms and the SMS 300 ms, and the bank gets 200 OK after 340 ms. On the right, the gateway takes 3,000 ms. The bank stops waiting at 1,000 ms (red) and sends P2 again, twice. Each send runs the ledger and the SMS again, so P2 is written three times and three receipts go out. Both sides are drawn to the same scale.On the left, P1 on a normal day: the ledger takes 40 ms and the SMS 300 ms, and the bank gets 200 OK after 340 ms. On the right, the gateway takes 3,000 ms. The bank stops waiting at 1,000 ms (red) and sends P2 again, twice. Each send runs the ledger and the SMS again, so P2 is written three times and three receipts go out. Both sides are drawn to the same scale.
The answer waits for the SMS, so a slow gateway makes the bank give up and send again. On the left, P1 on a normal day: the ledger takes 40 ms and the SMS 300 ms, and the bank gets 200 OK after 340 ms. On the right, the gateway takes 3,000 ms. The bank stops waiting at 1,000 ms (red) and sends P2 again, twice. Each send runs the ledger and the SMS again, so P2 is written three times and three receipts go out. Both sides are drawn to the same scale.

The idea

The pattern works like this:

  • The thread that receives the work does not do it. It puts the work in a buffer and returns at once.
  • Other threads take work from the buffer and do it at their own pace.
  • The buffer has a fixed size. A producer that finds it full waits a short time for room, and is refused if none appears. A consumer that finds it empty waits.
  • Closing the buffer refuses new work and lets the consumers finish what it holds before they stop.

The threads that put work in are the producers, and the threads that take it out are the consumers. The buffer is often called a queue. A full buffer making producers wait or refusing them is called backpressure: the slow side pushes back on the fast side instead of letting the waiting work grow without limit.

Building it, step by step

Step 1: the buffer and its lock

BoundedBuffer holds the waiting items in an array used as a ring:

queue/BoundedBuffer.javalines 17–33 of 144
public final class BoundedBuffer<T> {    private final Object[] items;    private int takeIndex;    private int putIndex;    private int count;    private boolean closed;     private final ReentrantLock lock = new ReentrantLock();    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();     public BoundedBuffer(int capacity) {        if (capacity < 1) {            throw new IllegalArgumentException("capacity must be at least 1, was " + capacity);        }        this.items = new Object[capacity];    }

putIndex is where the next item goes and takeIndex is where the next one comes from. Both move forward and wrap to 0 at the end of the array, so the array never shifts. count says how many slots are full, and closed says whether the buffer still accepts work. One ReentrantLock guards all five fields. Line 25 makes a condition for producers to wait on while the buffer is full, and line 26 one for consumers to wait on while it is empty.

Decision

How do waiting threads sleep and wake?

Spin until the state changes

A producer loops on count == items.length until a slot frees up. This needs no lock to wait, but a waiting thread burns a CPU core doing nothing, and the fields still need a lock to change safely.

synchronized with wait and notifyAll

Java's built-in monitor gives one waiting line per object. Producers and consumers wait in the same line, so every change has to wake all of them with notifyAll, and most go straight back to sleep. A plain notify can wake a producer when only a consumer could make progress, and then nobody moves.

One lock with two conditionsOur pick

Producers wait on notFull and consumers on notEmpty. A take frees one slot, so it wakes one producer. An offer adds one item, so it wakes one consumer. The cost is a lock that must be released in a finally on every path, which synchronized does by itself.

Step 2: offering an item

offer adds an item, waiting up to timeout for room:

queue/BoundedBuffer.javalines 35–62 of 144
    /** Adds the item, waiting up to timeout for room. */    public OfferResult offer(T item, Duration timeout) throws InterruptedException {        Objects.requireNonNull(item, "item");        Objects.requireNonNull(timeout, "timeout");        if (timeout.isNegative()) {            throw new IllegalArgumentException("timeout must not be negative, was " + timeout);        }        long nanos = TimeUnit.NANOSECONDS.convert(timeout);        lock.lockInterruptibly();        try {            while (!closed && count == items.length) {                if (nanos <= 0) {                    return OfferResult.FULL;                }                nanos = notFull.awaitNanos(nanos);            }            if (closed) {                return OfferResult.CLOSED;            }            items[putIndex] = item;            putIndex = (putIndex + 1) % items.length;            count++;            notEmpty.signal();            return OfferResult.ACCEPTED;        } finally {            lock.unlock();        }    }

Line 45 is a while, not an if. A producer can wake from line 49 because its time ran out, because a take signalled it but another producer took the free slot first, or for no reason at all, which Java allows and calls a spurious wake-up. In every case it must look at the buffer again before writing. With an if, a producer whose time ran out would write into a full buffer and overwrite the oldest item. awaitNanos returns the time still left, so several wake-ups share one timeout instead of each starting a new one.

The closed check on line 51 comes after the loop and before the write. A closed buffer answers CLOSED whether or not it has room, so a producer can tell "shutting down" from "full". Line 57 wakes one waiting consumer, if there is one.

CallbackEndpoint is the producer side. It runs on a web server thread and turns the result into the bank's answer:

payment/CallbackEndpoint.javalines 21–34 of 35
    /** Runs on a web server thread for each callback the bank sends. */    public Response receive(PaymentCallback callback) {        Objects.requireNonNull(callback, "callback");        try {            return switch (buffer.offer(callback, offerTimeout)) {                case ACCEPTED -> Response.OK;                case FULL -> Response.BUSY;                case CLOSED -> Response.SHUTTING_DOWN;            };        } catch (InterruptedException e) {            Thread.currentThread().interrupt(); // the server is stopping this thread; keep the flag for it            return buffer.isClosed() ? Response.SHUTTING_DOWN : Response.BUSY;        }    }
Decision

What does a producer do when the buffer is full?

Wait until there is room

No callback is ever refused. But when the gateway stalls, the buffer fills, and then every server thread waits on it. That is the first version's problem again, one step later.

Refuse at once

The server thread is never held. But a slot that would have freed up 2 ms later is not waited for, so a short burst turns into "busy" answers and callbacks the bank must send again.

Wait a short time, then answer busyOur pick

The endpoint waits up to 50 ms in the demo. A short burst is absorbed, and a stalled gateway costs each server thread about 50 ms before the bank is told to send again. The cost is a wait to choose, and some callbacks sent twice while the gateway is down.

Step 3: taking an item

take waits for an item and removes it:

queue/BoundedBuffer.javalines 64–84 of 144
    /** Waits for the next item. Empty means the buffer is closed and has nothing left. */    public Optional<T> take() throws InterruptedException {        lock.lockInterruptibly();        try {            while (count == 0) {                if (closed) {                    return Optional.empty();                }                notEmpty.await();            }            @SuppressWarnings("unchecked")            T item = (T) items[takeIndex];            items[takeIndex] = null;            takeIndex = (takeIndex + 1) % items.length;            count--;            notFull.signal();            return Optional.of(item);        } finally {            lock.unlock();        }    }

The loop on line 68 is a while for the same reasons as in offer. A consumer returns empty only when the buffer is closed and empty, so closing never strands an item that was accepted. Line 76 clears the slot so the buffer does not keep a taken callback alive, and line 79 wakes one waiting producer.

The buffer is first in, first out, so items leave in the order they were accepted. With one consumer, they are also settled in that order. With several consumers, two items can be taken in order and finished out of order, because one worker can be slower than another. If two callbacks for the same order must be settled in order, each order has to go to the same worker. That is a follow-up.

Step 4: the workers

SettlementWorkers starts a fixed number of consumer threads, and the endpoint takes no callbacks until start returns. Each thread runs work:

payment/SettlementWorkers.javalines 74–112 of 179
    private void work() {        try {            while (!stopNow) {                Optional<PaymentCallback> next;                try {                    next = buffer.take();                } catch (InterruptedException e) {                    continue; // only shutdownNow stops a worker; other interrupts are dropped                }                if (next.isEmpty()) {                    return; // closed and empty                }                settle(next.get());            }        } finally {            try {                if (taking.decrementAndGet() == 0 && !stopNow) {                    // Nobody is left to settle: stop accepting, and keep what was waiting.                    for (PaymentCallback stranded : buffer.closeAndDrain()) {                        failed.add(new FailedCallback(stranded, "no worker left to settle it"));                    }                }            } finally {                alive.decrementAndGet(); // only now has this worker stopped            }        }    }     private void settle(PaymentCallback callback) {        try {            processor.settle(callback);            settled.incrementAndGet();        } catch (Throwable e) { // checked exceptions can arrive undeclared, so catch everything            failed.add(new FailedCallback(callback, describe(e)));            if (e instanceof Error error) {                throw error; // an Error ends this worker; the others carry on            }        }    }

A worker takes callbacks until take returns empty, which happens once the buffer is closed and empty. Only shutdownNow (Step 5) or an Error stops it sooner. Any other interrupt, even one a processor left set, is dropped on line 81. Each callback is settled inside its own try, so one failure does not stop the worker.

Decision

What happens when settling a callback throws?

Let the worker stop

The exception ends the worker thread. With four workers, four bad callbacks stop all settling, while the endpoint keeps answering 200 OK.

Put the callback back in the buffer

It is tried again later. If it fails every time, such as a payment for an order the ledger does not know, it goes round for ever and takes a slot from good callbacks.

Keep it in a failed list and go onOur pick

Line 107 records the callback with the exception's text, and the worker takes the next one. Line 106 catches every Throwable, because a checked exception can be thrown without being declared. If the exception's toString throws or returns null, the reason is its class name. A person or a retry job calls drainFailed(), which removes what it returns, so each failure is handed out once. An Error is recorded too, then ends that worker on line 109. We choose that here, because settling payments in a program that may be broken is worse than stopping. A general thread pool cannot know that, and keeps the task's Error for its caller. If that was the last worker, line 92 closes the buffer, so the endpoint stops answering 200 OK for work nobody will settle. The callbacks still waiting move to the failed list with the reason "no worker left to settle it". Line 97 counts the worker as stopped only after that, so awaitTermination cannot say true too early. aliveWorkers() lets a health check notice, as writerAlive() does in the Logging Framework design. The cost is that a failure is only noticed if someone reads the list.

Step 5: shutting down

close marks the buffer closed and wakes every waiting thread:

queue/BoundedBuffer.javalines 86–96 of 144
    /** Refuses every later offer and wakes every waiting thread. Calling it again does nothing more. */    public void close() {        lock.lock();        try {            closed = true;            notFull.signalAll();            notEmpty.signalAll();        } finally {            lock.unlock();        }    }

SettlementWorkers splits shutdown into two calls, the way Java's ExecutorService does:

payment/SettlementWorkers.javalines 133–160 of 179
    /** Stops accepting callbacks. The workers settle what was already accepted, then stop. */    public void shutdown() {        buffer.close();    }     /**     * Stops accepting, takes back every callback not yet started, and interrupts the     * workers. Returns the callbacks taken back, so they can be kept somewhere else.     */    public List<PaymentCallback> shutdownNow() {        stopNow = true;        List<PaymentCallback> notStarted = buffer.closeAndDrain();        threads.forEach(Thread::interrupt);        return notStarted;    }     /** Waits up to timeout. True if every worker has stopped. */    public boolean awaitTermination(Duration timeout) throws InterruptedException {        long wait = TimeUnit.NANOSECONDS.convert(Objects.requireNonNull(timeout, "timeout"));        long start = System.nanoTime();        for (Thread thread : threads) {            long left = wait - (System.nanoTime() - start);            if (left > 0) {                TimeUnit.NANOSECONDS.timedJoin(thread, left);            }        }        return alive.get() == 0; // the last worker to stop leaves the buffer closed and empty    }

shutdown closes the buffer and returns at once. From then on, every offer answers CLOSED, including producers that were waiting for room, because BoundedBuffer.close wakes them and the closed check in offer refuses them. Consumers keep taking until the buffer is empty, and then take returns empty and each worker stops. awaitTermination waits a bounded time, and returns true once every worker has stopped. The last worker leaves the buffer closed and empty.

If it returns false, a worker is probably stuck, perhaps on the SMS gateway. shutdownNow then takes back every callback no worker has started and interrupts the workers (lines 144 and 145), like Java's ExecutorService.shutdownNow. closeAndDrain closes and empties the buffer under one lock, so no offer can slip in between and be stranded. Each callback it returns was answered 200 OK, so the caller must keep it somewhere that lasts. An interrupt in the middle of settle can leave the ledger written and no SMS sent, and if settle then throws, the callback goes to the failed list. Unless the thread factory makes daemon threads, a worker that ignores the interrupt keeps the program running.

The lock puts every offer either before close, where it can be accepted, or after it, where it is refused. take never returns empty while the buffer holds an item.

Decision

How do the consumers learn to stop?

A stop item for each consumer

Shutdown offers one special stop item, often called a poison pill, for every consumer, and each consumer stops when it takes one. This works with Java's BlockingQueue, which has no close. But the stop items wait behind a full buffer like any other item, the code must know how many consumers there are, and an item offered after the last stop item is never taken. The Logging Framework design uses one stop item and a lock to keep later records out.

A closed flag inside the bufferOur pick

The buffer itself knows it is closed. Producers are refused under the same lock that adds items, and consumers stop only when it is closed and empty. Nothing needs to know how many consumers exist. The cost is writing our own buffer, because BlockingQueue has no such flag.

Interrupt the workers

take throws InterruptedException at once. But a worker interrupted while the buffer still holds items stops early, and those items are left behind. Ours stops on an interrupt only from shutdownNow, which takes the waiting items back first.

Step 6: many producers, many consumers

demo/RaceCheck.java runs six producer threads, each sending 2,000 callbacks, through a buffer of 16 to four workers. A producer that is told "busy" sends the same callback again, as the bank would:

$ java demo.RaceCheck
6 producers sent 12000 callbacks through a buffer of 16 to 4 workers
accepted:                12000
settled exactly once:    12000
settled more than once:  0
never settled:           0
each worker took each producer's callbacks in the order sent: true
every worker stopped after shutdown: true

Every callback was accepted and settled exactly once. Each worker also saw any one producer's callbacks in the order that producer sent them, because the buffer is first in, first out. Without the lock, two producers can write into the same slot, so one callback is lost. Two workers can also take from the same slot: both get the same callback, so a payment is settled twice, or the second finds the slot already empty.

The finished design

The finished design
CallbackEndpoint offers each PaymentCallback to a BoundedBuffer and turns its OfferResult into a Response. SettlementWorkers owns the worker threads, which take from the same buffer and call a PaymentProcessor. A processor that throws leaves a FailedCallback in the failed list. PaymentProcessor is an interface for the ledger and the SMS gateway outside our code.CallbackEndpoint offers each PaymentCallback to a BoundedBuffer and turns its OfferResult into a Response. SettlementWorkers owns the worker threads, which take from the same buffer and call a PaymentProcessor. A processor that throws leaves a FailedCallback in the failed list. PaymentProcessor is an interface for the ledger and the SMS gateway outside our code.
The buffer knows nothing about payments; the endpoint and the workers sit on either side of it. CallbackEndpoint offers each PaymentCallback to a BoundedBuffer and turns its OfferResult into a Response. SettlementWorkers owns the worker threads, which take from the same buffer and call a PaymentProcessor. A processor that throws leaves a FailedCallback in the failed list. PaymentProcessor is an interface for the ledger and the SMS gateway outside our code.

Here is one callback, traced from the bank to the worker:

One callback, traced
The bank calls receive (1). The endpoint offers the callback to the buffer (2), which takes the lock, writes the callback and signals a waiting worker (3). The offer returns ACCEPTED, and the endpoint answers 200 OK (4). The worker was waiting in take. It wakes, removes the callback and signals a waiting producer (5), and take returns P1 (6). The worker calls settle on the processor (7). Steps 5 to 7 can happen before or after step 4, because they run on another thread.The bank calls receive (1). The endpoint offers the callback to the buffer (2), which takes the lock, writes the callback and signals a waiting worker (3). The offer returns ACCEPTED, and the endpoint answers 200 OK (4). The worker was waiting in take. It wakes, removes the callback and signals a waiting producer (5), and take returns P1 (6). The worker calls settle on the processor (7). Steps 5 to 7 can happen before or after step 4, because they run on another thread.
The bank's answer comes back after the offer; settling happens later on another thread. The bank calls receive (1). The endpoint offers the callback to the buffer (2), which takes the lock, writes the callback and signals a waiting worker (3). The offer returns ACCEPTED, and the endpoint answers 200 OK (4). The worker was waiting in take. It wakes, removes the callback and signals a waiting producer (5), and take returns P1 (6). The worker calls settle on the processor (7). Steps 5 to 7 can happen before or after step 4, because they run on another thread.

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

queueBoundedBuffer.java
package queue; import java.time.Duration;import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Optional;import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock; /** * A fixed-size, first-in first-out buffer between threads that add items and * threads that take them. Once closed, it accepts nothing new and still hands * out every item it already holds. */public final class BoundedBuffer<T> {    private final Object[] items;    private int takeIndex;    private int putIndex;    private int count;    private boolean closed;     private final ReentrantLock lock = new ReentrantLock();    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();     public BoundedBuffer(int capacity) {        if (capacity < 1) {            throw new IllegalArgumentException("capacity must be at least 1, was " + capacity);        }        this.items = new Object[capacity];    }     /** Adds the item, waiting up to timeout for room. */    public OfferResult offer(T item, Duration timeout) throws InterruptedException {        Objects.requireNonNull(item, "item");        Objects.requireNonNull(timeout, "timeout");        if (timeout.isNegative()) {            throw new IllegalArgumentException("timeout must not be negative, was " + timeout);        }        long nanos = TimeUnit.NANOSECONDS.convert(timeout);        lock.lockInterruptibly();        try {            while (!closed && count == items.length) {                if (nanos <= 0) {                    return OfferResult.FULL;                }                nanos = notFull.awaitNanos(nanos);            }            if (closed) {                return OfferResult.CLOSED;            }            items[putIndex] = item;            putIndex = (putIndex + 1) % items.length;            count++;            notEmpty.signal();            return OfferResult.ACCEPTED;        } finally {            lock.unlock();        }    }     /** Waits for the next item. Empty means the buffer is closed and has nothing left. */    public Optional<T> take() throws InterruptedException {        lock.lockInterruptibly();        try {            while (count == 0) {                if (closed) {                    return Optional.empty();                }                notEmpty.await();            }            @SuppressWarnings("unchecked")            T item = (T) items[takeIndex];            items[takeIndex] = null;            takeIndex = (takeIndex + 1) % items.length;            count--;            notFull.signal();            return Optional.of(item);        } finally {            lock.unlock();        }    }     /** Refuses every later offer and wakes every waiting thread. Calling it again does nothing more. */    public void close() {        lock.lock();        try {            closed = true;            notFull.signalAll();            notEmpty.signalAll();        } finally {            lock.unlock();        }    }     /**     * Closes the buffer and removes every item it still held, oldest first, in one     * step, so no offer can slip in between. Wakes every waiting thread.     */    public List<T> closeAndDrain() {        lock.lock();        try {            closed = true;            List<T> drained = new ArrayList<>(count);            while (count > 0) {                @SuppressWarnings("unchecked")                T item = (T) items[takeIndex];                drained.add(item);                items[takeIndex] = null;                takeIndex = (takeIndex + 1) % items.length;                count--;            }            notFull.signalAll();            notEmpty.signalAll();            return drained;        } finally {            lock.unlock();        }    }     public int size() {        lock.lock();        try {            return count;        } finally {            lock.unlock();        }    }     public int capacity() {        return items.length;    }     public boolean isClosed() {        lock.lock();        try {            return closed;        } finally {            lock.unlock();        }    }}
Click a class name in the code to open its fileJava · 144 lines · 714 in the project

demo/Main.java runs the service with a buffer of 2 and one worker, so the output is the same on every run. Its stand-in processor can stall like an SMS gateway that stops answering, and it refuses order 0000:

$ java demo.Main
1. A callback is answered at once and settled after
   bank -> P1 (order 8841, $150.00): 200 OK
   settled P1

2. The SMS gateway stalls
   bank -> P2 (order 8842, $99.00): 200 OK
   the worker is stuck on P2, waiting for the gateway
   bank -> P3 (order 8843, $220.00): 200 OK   [buffer 1 of 2]
   bank -> P4 (order 8844, $45.00): 200 OK   [buffer 2 of 2]
   bank -> P5 (order 8845, $310.00): 503 busy, send it again later   [buffer 2 of 2]

3. The gateway recovers
   settled P2
   settled P3
   settled P4
   the bank sends P5 again
   bank -> P5 (order 8845, $310.00): 200 OK
   settled P5

4. The ledger refuses one payment
   bank -> P6 (order 0000, $120.00): 200 OK
   bank -> P7 (order 8847, $180.00): 200 OK
   failed P6: java.lang.IllegalArgumentException: ledger has no order 0000
   settled P7

5. Shutting down while a payment is being settled
   bank -> P8 (order 8848, $60.00): 200 OK
   bank -> P9 (order 8849, $275.00): 200 OK   [buffer 1 of 2]
   shutdown has started: the buffer is closed
   bank -> P10 (order 8850, $80.00): 503 shutting down, send it again later   [buffer 1 of 2]
   settled P8
   settled P9
   every worker has stopped: true

accepted 9, settled 8, failed 1, refused 2 (1 busy, 1 shutting down)

Part 1 is requirement 1: P1 is answered at once and settled on the worker's thread. In part 2 the gateway stalls with the worker on P2, so P3 and P4 fill the buffer and P5 is answered busy after 50 ms (requirements 3 and 4). In part 3, P2 to P4 are settled in the order they arrived, and the bank's second send of P5 is accepted. Part 4 is requirement 6: P6 is answered 200 OK, fails at the ledger and is kept, and the worker goes on to P7. Part 5 is requirement 7. Shutdown starts with P8 being settled and P9 waiting. P10 is told "shutting down", not "busy", and P8 and P9 are still settled before the worker stops.

What it costs

200 OK now means accepted, not settled. The bank hears "OK" before the ledger does. A failure happens after the answer, so we must keep it and act on it, through the failed list, instead of the bank sending again.

A payment can still be settled twice. The buffer makes repeats rarer, not impossible. If our 200 OK is lost on the network, the bank sends P1 again and we accept it as a new delivery. If a retry job retries a callback whose ledger line was written before the SMS failed, the ledger gets a second line. So settling must be safe to repeat: the ledger keys each line on the payment id and refuses a second one, and the receipt sender records which payments it has sent.

Accepted work lives in memory. A crash after the 200 OK loses the callbacks in the buffer and in the workers' hands, and the bank will not send them again, so those orders stay unpaid. In production, the endpoint writes each callback to a database table keyed on the payment id before it answers 200 OK. The key also catches repeats, and the workers read from the table. The buffer on this page stands in for that table.

The size is a guess you have to tune. Too small, and a short burst turns into "busy" answers. Too large, and callbacks wait a long time to be settled. A buffer absorbs bursts only: if callbacks arrive faster than the workers settle them for minutes on end, any size fills, and the fix is more workers or faster settling.

One slow step holds up the others. A stalled SMS gateway also delays marking orders paid. Receipts can go on a second buffer with their own workers, so the two stay apart.

What the buffer changes
Before, the bank's answer waits for the ledger and the SMS, a failed settle reaches the bank as an error, and after a crash the bank sends the callback again. After, the answer waits only for the offer (purple), and the work happens later on a worker. A failed settle goes to our failed list, and a crash loses what the buffer and the workers held (red).Before, the bank's answer waits for the ledger and the SMS, a failed settle reaches the bank as an error, and after a crash the bank sends the callback again. After, the answer waits only for the offer (purple), and the work happens later on a worker. A failed settle goes to our failed list, and a crash loses what the buffer and the workers held (red).
The answer gets fast and steady; the result arrives later and must be watched. Before, the bank's answer waits for the ledger and the SMS, a failed settle reaches the bank as an error, and after a crash the bank sends the callback again. After, the answer waits only for the offer (purple), and the work happens later on a worker. A failed settle goes to our failed list, and a crash loses what the buffer and the workers held (red).

When a buffer is too much

If settling is quick and calls nothing slow, doing it inline is simpler and has none of the costs above. If the work is slow but you do not need your own buffer, Java already has one. In production, an ArrayBlockingQueue is a bounded buffer that is far more tested than ours:

Sketchnot part of the final code
BlockingQueue<PaymentCallback> queue = new ArrayBlockingQueue<>(1_000); boolean accepted = queue.offer(callback, 50, TimeUnit.MILLISECONDS);   // a producerPaymentCallback next = queue.take();                                   // a consumer

ArrayBlockingQueue is built much like ours, with one lock and two conditions. LinkedBlockingQueue uses one lock for adding and another for taking. Neither has a close, so shutdown uses a stop item for each consumer. Executors.newFixedThreadPool puts its tasks on an unbounded LinkedBlockingQueue, so it never pushes back. When its bounded queue is full and it already runs its maximum number of threads, a ThreadPoolExecutor refuses the task at once with its default AbortPolicy.

Producer-Consumer, Observer or a thread pool?

ObserverProducer-ConsumerThread pool
Who does the workEach listener, on the subject's threadConsumer threadsThe pool's threads
WhenDuring the subject's call, one after anotherLater, at the consumers' paceLater, when a thread is free
What is handed overAn event, by a method callAn item, through a bufferA task to run, through the pool's queue
If the receiver is slowThe subject waitsThe buffer fills, then producers wait or are refusedTasks wait in the pool's queue, then are refused, if the queue is bounded
ExampleA score service updating its scoreboardPayment callbacks settled by workersResizing uploaded photos

The Observer pattern page compares Observer with a message queue such as RabbitMQ, which connects separate programs. A message queue is Producer-Consumer across programs, and the buffer on this page is the same idea inside one program.

A short way to say it: Observer calls the receivers now, and Producer-Consumer hands the work over to be done later. A thread pool is a Producer-Consumer whose items are tasks.

In an interview

The pattern is inside any question with work that arrives faster than it can be done: a logger with a background writer, a job queue, a web crawler, or a request to write a bounded blocking queue.

A good order for presenting it:

  1. Say what is fast and what is slow. "The bank needs an answer in a second, and the SMS can take three."
  2. Draw producers, the buffer and consumers. Say what happens when the buffer is full, when it is empty, and at shutdown.
  3. Then write the buffer: one lock, two conditions, a while around every wait, and a close that refuses producers and lets consumers drain.

Common mistakes:

  • An if around the wait. A thread that wakes without its condition being true writes into a full buffer or reads from an empty one.
  • One waiting line with a single notify. A producer's notify can wake another producer instead of a waiting consumer, and the consumer that could have taken the item sleeps on.
  • No limit on the buffer. When consumers fall behind, the waiting work grows until memory runs out, and nothing tells the producers to slow down.
  • A shutdown that drops work. Clearing the buffer or interrupting the consumers loses callbacks that were already answered 200 OK.
  • Letting one bad item kill a consumer. The workers die one by one while producers keep being told the work was accepted.

Summary

  • Use Producer-Consumer when work must be received quickly but done slowly, or done by several threads at once.
  • Put a bounded buffer between producers and consumers, and decide what a producer gets when it is full.
  • Guard the buffer with one lock and two conditions, and wrap every wait in a while.
  • Close the buffer to shut down: refuse new work, let consumers drain what was accepted, then let them stop.
  • Keep a failed item with its reason, so one bad item neither stops a consumer nor disappears.
  • Accepted is not done: the answer is fast because the work happens later.

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.