What Problem It Solves
A producer-consumer problem appears whenever one part of a program creates work at a different speed from the part that finishes it. Request threads produce log lines, orders or image jobs, and worker threads consume them. A blocking queue sits between the two sides and gives them three things at once: a buffer that is safe to share, waiting that costs no CPU, and a limit on how far ahead the producers can get.
| Approach | What goes wrong | What the fix must provide |
|---|---|---|
| Plain shared list, no lock | An append is three steps (read the size, write the slot, write the size), so two threads can write the same slot and one item vanishes. A racing resize can also throw. The failure tab on this page loses a large fraction of 400,000 appends on a typical run. | Every mutation happens under one lock, so the buffer is only ever seen in a consistent state. |
Busy waiting, while (list.isEmpty()) {} | The consumer burns a full core to learn nothing. In the failure tab it spins more than 10,000 times to wait 50 ms for one item, and it competes for CPU with the producer that must run to end the wait. | A waiting thread must be parked by the scheduler and woken exactly when the state changes. |
Polling with sleep, sleep(10 ms) between checks | It trades CPU for latency. Every item waits half the poll period on average (about 5 ms here), and an idle consumer still wakes 100 times a second. | Wake-up on the event itself, not on a timer. |
| Unbounded buffer | If producers make 1,000 items a second and consumers finish 800, the backlog grows by 200 a second. After ten minutes that is 120,000 items, about 120 MB at 1 KB each, and the newest item waits 150 seconds. Memory runs out before the producers ever slow down. | A capacity limit that makes producers wait, which is called backpressure. |
A bounded blocking queue promises four things. Mutations are serialised, so no item is lost or duplicated. A take parks the caller while the queue is empty. A put parks the caller while the queue is full. Items leave in the order they arrived.
How a Blocking Queue Works
One lock guards all of the state. Two condition variables, notFull and notEmpty, name the two reasons a thread might have to wait, so a producer is only ever woken by a freed slot and a consumer is only ever woken by a new item. The ring buffer keeps a head index for the oldest item, a tail index for the next free slot, and a count.
Because await releases the lock while the thread is parked, a waiting producer never stops a consumer from taking the item that will wake it. Releasing the lock and joining the wait list happen as one atomic step, which is what closes the lost-wakeup window described below.
Worked Trace With Capacity 3
Three producers P1 to P3 and one consumer C1 share a queue of capacity 3. Each row is one step, and the Queue column is the content after that step, oldest item first.
| Step | Actor | What happens | Queue after |
|---|---|---|---|
| 1 | C1 | take() finds count 0 and parks on notEmpty | empty, C1 parked |
| 2 | P1 | put(A) stores A and signals notEmpty, so C1 becomes runnable but must still win the lock | A |
| 3 | P2 | put(B) gets the lock before C1 does (this is called barging), stores B and signals again with nobody left to wake | A, B |
| 4 | C1 | Resumes and tests the loop condition again. Count is 2, not 0, so it takes A and signals notFull, which wakes nobody | B |
| 5 | P1, P2 | put(C) and put(D) fill the queue to count 3, which equals capacity | B, C, D |
| 6 | P3 | put(E) finds count 3 and parks on notFull. This wait is the backpressure | B, C, D, P3 parked |
| 7 | C1 | take() returns B, count drops to 2, and notFull.signal() wakes P3 | C, D |
| 8 | P3 | Wins the lock, tests again (count 2 is below 3), stores E and signals notEmpty | C, D, E |
Steps 3 and 4 are the reason the loop exists. C1 was woken because the queue had an item, but by the time it ran the queue had a different content, so it had to look again before acting.
Why a While Loop and Not an If
Every wait on a condition must sit inside a loop that tests the predicate again after waking. Three separate facts force this, and an interviewer expects you to name them.
| Fact | What happens | What goes wrong with an if |
|---|---|---|
| Spurious wakeup | A thread can return from await or wait although nobody signalled. Java's Condition.await documentation allows it and POSIX condition variables are specified the same way. | The consumer carries on with an empty queue and reads a stale slot or throws. |
| Barging (signal-and-continue) | A signal only makes the waiter runnable. The signaller keeps running and any other thread that reaches the lock first can take the item, as P2 did in step 3 of the trace. | The woken thread finds the item gone. The TypeScript tab prints this exact bug: with if, task a gets undefined and task b gets the item. |
| One signal, many waiters | With signalAll, every parked consumer wakes for a single new item, but only one can have it. | The losers each act on an empty queue. With the loop they re-test and park again. |
Lost wakeups are the opposite danger. A condition variable has no memory, so a signal sent while nobody is waiting is simply forgotten. If a consumer checks the queue outside the lock, finds it empty and only then starts to wait, a producer's signal can land in that gap and the consumer sleeps forever beside a non-empty queue. The cure has two parts. The check and the wait both happen under the same lock, and producers change the state under that lock before they signal. A semaphore behaves differently because its count is a memory, so a release before the acquire is not lost.
Signal Versus SignalAll
The two calls differ in how many waiters they wake, and the right one depends on whether every waiter on the condition is waiting for the same thing.
| Call | Wakes | Use when | Risk or cost |
|---|---|---|---|
signal / notify | One waiter, usually the longest waiting one in the JDK | All waiters share one predicate and a state change lets exactly one of them proceed. A put frees one item for one consumer, so this page uses it. | If waiters wait for different things on one condition, the signal can wake the wrong kind and the wake-up is wasted, which can deadlock the queue. |
signalAll / notify_all | Every waiter, each of which re-tests under the lock | One change can unblock many threads, such as shutdown, clear(), or a bulk insert that frees several slots at once. Also when one condition serves mixed waiters. | A thundering herd. With 100 parked consumers, one new item causes 100 wake-ups and 99 go straight back to sleep. |
| Cascading signal | One waiter, which then wakes the next if more work remains | You want the low cost of signal with batch-safe behaviour. LinkedBlockingQueue.take does this by signalling another taker when items are still left. | More code to get right, so prefer the library class. |
This is why the code on this page uses two conditions. With a single condition and signal, take a capacity-1 queue that is full with producers P2 and P3 parked. Consumer C1 takes the item and the signal selects P2, but P2 has not run yet. Consumer C2 arrives, sees an empty queue and parks on the same condition behind P3. P2 now runs, stores an item and signals, and the signal selects P3, which finds the queue full and parks again. The queue is full, C2 is asleep, and nobody is left to signal it. Splitting the condition makes this impossible because a put can only ever wake a consumer.
Bounded Versus Unbounded and Backpressure
The bound is what turns a queue into a flow-control device. Once the buffer is full, a put waits, so the producers can run no faster than the consumers drain. Size the bound with the relation capacity equals drain rate times the wait you will tolerate. Four consumers that each need 50 ms per item drain 80 items a second, and a tolerated wait of 100 ms gives a capacity of 8, which is the value the drivers on this page use.
| Policy when full | Call | Effect | Use when |
|---|---|---|---|
| Block | put, queue.put(), await queue.put() | The producer waits and nothing is lost, so its rate drops to the consumer rate. | Internal pipelines. On a request thread, pair it with a timeout so callers are not stuck. |
| Fail fast | offer(x) returns false, put_nowait raises queue.Full | The caller learns at once and decides what to do. | A request path that can answer 429 or 503. |
| Wait with a limit | offer(x, 50, MILLISECONDS), put(x, timeout=0.05) | A bounded wait, then the caller gives up. | Soft real-time paths with a latency budget. |
| Drop | offer, then discard on false | Lossy, but the producer never stalls. The Logger Library blueprint drops the new record and warns. | Logs and metrics, where losing some is better than slowing the application. |
| Run in the caller | ThreadPoolExecutor.CallerRunsPolicy | The submitting thread does the work itself, so it cannot submit more while it is busy. | Thread pools that need natural throttling. |
An unbounded queue is not a safe default. Executors.newFixedThreadPool is built on an unbounded LinkedBlockingQueue, so a slow consumer shows up as growing memory instead of slowed producers. A ThreadPoolExecutor with an unbounded queue also never grows past its core size, because it only starts extra threads when the queue refuses an offer, so its maximum pool size is never used. For the system-level view of the same idea, see Backpressure and Load Shedding, and for brokers that put a durable queue between services, see Message Queues Fundamentals.
Shutdown With a Poison Pill or an Interrupt
Consumers spend their time parked inside take, so a shared running flag alone cannot stop them because they never get to read it. Something has to wake them, and there are three common choices.
| Approach | How it works | Strength | Pitfalls |
|---|---|---|---|
| Poison pill | A producer enqueues a sentinel that a consumer recognises and exits on. All three hand-built tabs use it. | FIFO order means every item ahead of the pill is processed first, so shutdown loses nothing. No special API is needed. | Send one pill per consumer, because with 4 consumers and 3 pills one consumer parks forever and keeps a non-daemon JVM alive. Send pills only after every producer has finished, or consumers stop while items are still coming. |
| Interrupt (Java) | shutdownNow() or thread.interrupt() makes a parked take throw InterruptedException. The ArrayBlockingQueue tab uses it. | Immediate, works on an empty queue and needs no sentinel value. | Items still in the queue are abandoned, so the tab waits for the queue to empty first. Swallowing the exception loses the stop request, so exit the loop or call Thread.currentThread().interrupt() to restore the flag. |
| Count completions | Python's task_done() and join() block until every item that was put has been marked finished, then daemon workers can be left to die with the process. | No sentinel and no knowledge of how many consumers exist. | If a worker raises before task_done(), join() waits forever, so call task_done() in a finally block as the Python tab does. |
Python 3.13 added Queue.shutdown(), which wakes blocked callers, makes later puts raise queue.ShutDown, and makes gets raise it once the queue is empty. JavaScript has no way to interrupt a parked promise, so an async queue relies on pills or on an AbortSignal that the parked call also listens to.
Many Producers and Many Consumers
Adding threads on either side does not change the queue code, because the lock already serialises every put and take. What changes is which guarantees you can lean on. The drivers on this page run 3 producers and 4 consumers and print the counts below to show each guarantee holding.
| Concern | What the queue gives you | What it does not give you |
|---|---|---|
| Delivery | Each item goes to exactly one consumer. The drivers print duplicates=0 missing=0 after 3,000 items in Java and Python and 1,500 in TypeScript. | Protection from a consumer that crashes after take. The queue has already forgotten that item, so processing is at most once unless you add acknowledgement and redelivery. |
| Order | FIFO overall, so each producer's items keep their order, and each consumer sees any one producer's items in increasing sequence. The drivers print orderViolations=0. | Ordered completion. Two consumers run in parallel, so item 7 can finish before item 6. For per-key order, route by hash(key) % N to N queues that each have one consumer. |
| Fairness | Parked threads are woken roughly in arrival order. | Strict fairness, because barging lets a running thread overtake a woken one. A fair lock, as in new ArrayBlockingQueue<>(n, true), restores order at a real throughput cost. |
| Bound | Each driver records the deepest backlog it saw and prints that it stayed within the capacity of 8, so memory stays flat however many producers run. | A bound on work in flight. Items already taken still occupy the consumers, so total outstanding work is capacity plus consumer count. |
Throughput Trade-offs
Correctness comes first, but a queue is often the hottest shared object in a service, so the lock layout matters. The usual levers are how many locks the queue has, how much work each lock acquisition covers, and whether the queue holds items at all.
| Design | Locking | Strength | Cost |
|---|---|---|---|
| ArrayBlockingQueue | One lock for both ends, over a fixed array | No allocation per item, predictable memory, optional fair mode. | Producers and consumers contend on the same lock. |
| LinkedBlockingQueue | Two locks, putLock for the tail and takeLock for the head, plus an atomic count | A producer and a consumer can run at the same time, so throughput is usually higher when both sides are busy. The put side only touches the take lock to signal that an empty queue became non-empty. | A node is allocated per item, and it is unbounded unless you pass a capacity. |
Batching, drainTo(list, 50) | One acquisition covers up to 50 items | At a million items a second, one acquire per item means a million lock operations a second per side, and batches of 50 cut that to 20,000. | Up to 50 items are in flight at once, so a crash loses more, and a producer that waits to fill a batch adds latency. |
| SynchronousQueue | No storage, a direct hand-off between one producer and one consumer | Zero buffering, so there is no backlog to grow. newCachedThreadPool is built on it. | A producer blocks until a consumer is ready, so bursts are not absorbed. |
| Lock-free ring buffer (Disruptor style) | Atomic sequence counters, no mutex | Lowest latency under heavy contention. | No built-in parking, so you add a wait strategy, and the code is far harder to reason about. Rarely right in an interview. |
The reasoning behind batching is that an uncontended lock acquire costs tens of nanoseconds, while a contended one that parks the thread costs microseconds, so fewer and larger critical sections win once many threads compete. Python's queue.Queue takes one mutex per operation and has no bulk call, so a hand-built queue would add a get_many that pops up to n items inside one with block. In the TypeScript queue there is no lock to batch, but the same idea reduces the number of promise wake-ups.
Building It With Semaphores Instead
The classic alternative to conditions uses two counting semaphores and a mutex. The slots semaphore starts at the capacity and counts free positions. The items semaphore starts at zero and counts filled positions. The mutex protects the buffer indices.
| Step | put(x) | take() |
|---|---|---|
| 1 | slots.acquire() waits for a free slot | items.acquire() waits for an item |
| 2 | mutex.lock() | mutex.lock() |
| 3 | Store x at the tail | Remove the item at the head |
| 4 | mutex.unlock() | mutex.unlock() |
| 5 | items.release() announces one more item | slots.release() announces one more free slot |
The order of steps 1 and 2 is the classic trap. If a producer takes the mutex first and then waits for a slot, it holds the lock that a consumer needs in order to free that slot, so both stop forever. Semaphores remember releases, which removes both the lost wakeup and the need for a loop. They fit pure counting well. Conditions are the better tool when the wait depends on richer state, such as the Job Scheduler, whose dispatcher waits for the head job to become due and not merely for the queue to be non-empty.
Common Interview Traps
| Trap | Why | Fix |
|---|---|---|
Using if instead of while around the wait | Spurious wakeups and barging mean the predicate can be false again by the time the woken thread runs | Always loop: while (count == 0) notEmpty.await() |
Check then act on a thread-safe queue, as in if (!q.isEmpty()) q.take() | Another consumer can empty the queue between the two calls, so take blocks forever. A size is already stale when it is returned. | Call take or poll and use its result. Use size() or qsize() for metrics only. |
One condition shared by producers and consumers with signal() | The signal can wake the wrong kind of thread, which parks again, and the right one sleeps forever | Use two conditions, notFull and notEmpty, or call signalAll |
| Doing the slow work while holding the lock | Every other producer and consumer waits for the slow item, so the queue serialises the whole pipeline | Move the item out under the lock, release it, then process |
| A consumer that also produces onto the same bounded queue | If every consumer is blocked in put on the full queue it drains, nobody is left to take, and the system deadlocks | Use a separate queue per stage, an unbounded feedback queue, or offer with a timeout |
| Fewer poison pills than consumers, or a pill sent before the last producer finishes | Surplus consumers park forever, or consumers quit while items are still arriving | Join every producer first, then enqueue exactly one pill per consumer |
Swallowing InterruptedException with an empty catch block | The stop request disappears and the consumer loops again | Exit the loop, or call Thread.currentThread().interrupt() to restore the flag |
| Defaulting to an unbounded queue | Executors.newFixedThreadPool uses an unbounded queue, so overload becomes memory growth and never reaches the producers | Give the queue a capacity and choose a policy for the full case, such as block, fail fast or run in the caller |
Calling await, wait or signal without holding the lock | Java throws IllegalMonitorStateException and Python raises RuntimeError, and the state check would not be atomic with the wait anyway | Wrap in lock.lock() with try and finally, or in a Python with block |
Skipping task_done() when processing raises | join() counts unfinished tasks and waits forever | Put task_done() in a finally block |
| Saying JavaScript has no race conditions, so no guard is needed | Each synchronous stretch is atomic, but an await between a check and the action lets other tasks run, which is the barging bug in the TypeScript tab | Re-test after every await, using promise queues as the waiting mechanism |
When to Use It and When Not To
| Situation | Verdict | Reason or alternative |
|---|---|---|
| Work can finish later and the caller does not need the result | Use a queue | Decouples request latency from processing time, and absorbs bursts up to the capacity. |
| Producers and consumers run at different or varying speeds | Use a bounded queue | The bound turns a speed mismatch into backpressure instead of memory growth. |
| The caller needs a reply | Use a future or a direct call | A queue returns nothing. Pair each item with a promise or Future if you must wait. |
| Items must survive a crash, or many services must read them | Use a broker | An in-memory queue dies with the process. Use a durable log or broker with acknowledgement. |
| Strict global order of completion | Use one consumer, or one queue per key | Parallel consumers finish out of order by design. |
| A fixed small set of tasks with no streaming | Skip the queue | A thread pool with invokeAll, or Promise.all, is simpler. |
How to Present in an Interview
"Producers and consumers run at different speeds, so I will put a bounded blocking queue between them. One lock guards a ring buffer and two conditions, notFull and notEmpty, name the reasons to wait. Each wait sits in a while loop because wake-ups can be spurious and another thread can take the item first. I will size the capacity as drain rate times tolerated wait, and when it is full producers block, which gives backpressure. For shutdown I will join the producers and then send one poison pill per consumer so everything queued is processed. In production I would use ArrayBlockingQueue or queue.Queue, and move to a broker if items must survive a restart."
Where It Shows Up in LLD Problems
Four problems put a queue or a condition between threads, and a fifth is worth comparing. The details below were read from each problem's blueprints and can differ by language.
| Problem | Where the queue is | What to notice |
|---|---|---|
| Logger Library | Java uses LinkedBlockingQueue<LogRecord>(1000) and Python uses queue.Queue(maxsize=1000). Callers offer or put_nowait, and one worker thread drains with a timed poll or get. The TypeScript blueprint uses an array capped at 1000. | The full-queue policy is drop, and a single consumer keeps sink writes in order. Shutdown drains with while (running || !queue.isEmpty()) rather than a pill. |
| Notification Service | Java uses an unbounded PriorityBlockingQueue drained by two workers that poll with a timeout and re-queue on a rate limit. Python keeps a list sorted under a Lock, and TypeScript an array, each with a worker that sleeps 50 ms when nothing is ready. | The Python and TypeScript workers poll, which is the sleep-and-check approach from the first table. Nothing bounds the Java queue, so a flood of submissions is not slowed. |
| Job Scheduler | The Java dispatcher holds a ReentrantLock with Condition entryAdded and waits in while (queue.isEmpty() && running), plus a timed await until the head job is due. schedule signals and shutdown calls signalAll. Due jobs go to a ThreadPoolExecutor. Python waits on a threading.Event with a timeout and TypeScript uses setInterval. | This is the pattern on this page with a timed wait, using signal for one new job and signalAll for shutdown. The executor's work queue is unbounded. |
| Thumbnail Service | Java uses LinkedBlockingQueue<String> of job ids, with a fixed set of workers that each loop on take() and are stopped by shutdownNow(). Python uses an unbounded queue.Queue with get(timeout=0.2) and task_done(). The TypeScript dequeue re-checks the array every 50 ms. | Interrupt-based shutdown in Java, and a polling consumer in TypeScript where the async queue on this page would wake on arrival. |
| Pub-Sub System | No blocking queue. Each partition is an append-only list with a synchronized append, and consumer groups track offsets and poll for new messages. | Reading does not remove items and never blocks, so many groups can read the same messages. A take-based queue gives each item to exactly one consumer. |
Implementation
Each runnable tab ends in a driver that prints the proof. The hand-built queues run 3 producers and 4 consumers on a capacity of 8, then print how many items were produced, consumed and distinct, plus duplicate, missing and out-of-order counts. The library tabs show the same job on the standard queue, and one Java tab shows the naive versions failing.
// โโโ HAND-BUILT BOUNDED BLOCKING QUEUE โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
// WHAT WE ARE IMPLEMENTING:
// A fixed-capacity FIFO queue whose put() blocks while full and whose take()
// blocks while empty, then a driver with 3 producers and 4 consumers.
//
// INVARIANT (holds whenever the lock is free):
// 0 <= count <= capacity, and the live items sit in slots head..head+count-1
// (mod capacity). Every field below is touched only while holding `lock`.
//
// WHERE THE PATTERN FITS IN:
// One lock guards the state, and two conditions name the two reasons to wait.
// notFull wakes producers, notEmpty wakes consumers, so a signal never has to
// guess which kind of thread it is waking.
// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class BoundedBlockingQueue<T> {
private final Object[] slots;
private int head = 0; // index of the oldest item
private int tail = 0; // index of the next free slot
private int count = 0; // number of live items
private int maxDepth = 0;
private final ReentrantLock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
BoundedBlockingQueue(int capacity) {
if (capacity < 1) throw new IllegalArgumentException("capacity must be >= 1");
this.slots = new Object[capacity];
}
void put(T item) throws InterruptedException {
lock.lockInterruptibly();
try {
while (count == slots.length) { // while, never if
notFull.await(); // releases the lock while parked
}
slots[tail] = item;
tail = (tail + 1) % slots.length;
count++;
maxDepth = Math.max(maxDepth, count);
notEmpty.signal(); // one new item wakes one consumer
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
T take() throws InterruptedException {
lock.lockInterruptibly();
try {
while (count == 0) { // while, never if
notEmpty.await();
}
T item = (T) slots[head];
slots[head] = null; // do not retain the reference
head = (head + 1) % slots.length;
count--;
notFull.signal(); // one freed slot wakes one producer
return item;
} finally {
lock.unlock();
}
}
int maxDepth() {
lock.lock();
try { return maxDepth; } finally { lock.unlock(); }
}
}
public class Main {
static final int PRODUCERS = 3, CONSUMERS = 4, PER_PRODUCER = 1000, CAPACITY = 8;
static final Integer POISON = -1; // real items are producer * 10000 + sequence
public static void main(String[] args) throws Exception {
BoundedBlockingQueue<Integer> queue = new BoundedBlockingQueue<>(CAPACITY);
Set<Integer> seen = ConcurrentHashMap.newKeySet();
AtomicInteger consumed = new AtomicInteger();
AtomicInteger duplicates = new AtomicInteger();
AtomicInteger orderViolations = new AtomicInteger();
Thread[] producers = new Thread[PRODUCERS];
for (int p = 0; p < PRODUCERS; p++) {
final int id = p;
producers[p] = new Thread(() -> {
try {
for (int s = 0; s < PER_PRODUCER; s++) queue.put(id * 10000 + s);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
Thread[] consumers = new Thread[CONSUMERS];
for (int c = 0; c < CONSUMERS; c++) {
consumers[c] = new Thread(() -> {
int[] lastSeq = new int[PRODUCERS];
java.util.Arrays.fill(lastSeq, -1);
try {
while (true) {
Integer item = queue.take();
if (item.equals(POISON)) break; // poison pill: stop cleanly
int producer = item / 10000, seq = item % 10000;
if (seq <= lastSeq[producer]) orderViolations.incrementAndGet();
lastSeq[producer] = seq;
if (!seen.add(item)) duplicates.incrementAndGet();
consumed.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
for (Thread t : consumers) t.start();
for (Thread t : producers) t.start();
for (Thread t : producers) t.join();
for (int c = 0; c < CONSUMERS; c++) queue.put(POISON); // one pill per consumer
for (Thread t : consumers) t.join();
int expected = PRODUCERS * PER_PRODUCER;
Set<Integer> missing = new HashSet<>();
for (int p = 0; p < PRODUCERS; p++)
for (int s = 0; s < PER_PRODUCER; s++)
if (!seen.contains(p * 10000 + s)) missing.add(p * 10000 + s);
System.out.println("produced=" + expected + " consumed=" + consumed.get()
+ " distinct=" + seen.size());
System.out.println("duplicates=" + duplicates.get() + " missing=" + missing.size()
+ " orderViolations=" + orderViolations.get());
System.out.println("maxDepth<=capacity: " + (queue.maxDepth() <= CAPACITY)
+ " (capacity " + CAPACITY + ")");
System.out.println(consumed.get() == expected && seen.size() == expected
&& duplicates.get() == 0 && missing.isEmpty() ? "PASS" : "FAIL");
}
}Review
How helpful was this walkthrough?
Click a star to rate. We actively use this feedback to refine and update our system design content.
Discussion
Share your thoughts, ask questions, or help others.