Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Implement a Thread-Safe
Bounded Blocking Queue.

An unbounded queue causes OOM crashes under producer bursts, while a naive synchronized bounded queue with if checks and notify() suffers from missed signals, spurious wakeups, and producer-consumer lock contention.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, implement a fixed-capacity circular ring buffer protected by a `ReentrantLock` with separate `notFull` and `notEmpty` `Condition` queues (or two-lock split), always guarding `await()` inside a `while` loop.

TL;DR30-second simplified summary
▾

Core Mechanics: In a telemetry pipeline with 16 producer threads bursting to 150,000 events/sec and 8 consumer threads, an unbounded LinkedBlockingQueue caused 4 GB JVM OOM crashes during downstream outages.

Visual & Structural Flow: Depicts Separate notFull & notEmpty Condition Queues (PUT (Producer) -> RING BUFFER [N] -> TAKE (Consumer)); Producer Blocking, Signal Handoff & Timed Shedding (Producer (16) -> ReentrantLock -> Ring [N] -> Consumer (8)).

Trade-Offs & Production: Using synchronized (this) with if (count == items.length) wait(); and notify() has three fatal bugs: (1) if fails on spurious wakeups or when another producer steals the. Implement an ArrayBlockingQueue-style ring buffer with ReentrantLock and two Condition queues: Fixed Ring Buffer (Object[capacity]): Maintain putIndex, takeIndex.

Failure Modes & Application: Bounded ring buffers are the backbone of high-throughput in-process pipelines: Log & Telemetry Shippers: Absorbs micro-bursts while applying backpressure (429) when disk/network sinks stall.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Bounded Blocking Queues Matter.

Why this matters: The mechanism: understand how Why Bounded Blocking Queues Matter works from first principles.

In a telemetry pipeline with 16 producer threads bursting to 150,000 events/sec and 8 consumer threads, an unbounded LinkedBlockingQueue caused 4 GB JVM OOM crashes during downstream outages. Replacing it with a naive synchronized queue caused deadlocks and IndexOutOfBoundsException.

Constraints:

  • Zero Thread.sleep polling / busy-waiting.
  • Fixed array-backed ring buffer (O(1) enqueue/dequeue, zero per-node GC allocation).
  • Sustain 150,000 ops/sec across 24 concurrent threads with clean InterruptedException handling.
02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Unbounded or Broken Queues.

Why this matters: The problem: see what breaks without Real-World Impact of Unbounded or Broken Queues under real concurrency or scale.

Queue misconfigurations break both memory safety and thread liveness:

  1. OOM Crashes: Unbounded queues absorb downstream stalls in heap until the JVM hits OutOfMemoryError.
  2. Missed Signals & Deadlocks: Calling notify() on a single monitor wakes an arbitrary thread—a producer can wake another producer when the queue is full, leaving consumers asleep forever.
  3. Spurious Wakeup Corruption: Using if (count == capacity) instead of while lets a woken thread overwrite an unconsumed slot or underflow count.
Bounded Ring Buffer Synchronization

Separate notFull & notEmpty Condition Queues

enqueue -> notEmpty.signal()dequeue -> notFull.signal()PUT (Producer)while(count==N) notFull.RING BUFFER [N]O(1) circular arrayTAKE (Consumer)while(count==0) notEmpty

Separate Condition queues ensure producers only wake consumers and consumers only wake producers, eliminating missed signals.

Engineering Decision Framework
Problem
How to implement Implement a Thread-Safe Bounded Blocking Queue without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, implement a fixed-capacity circular ring buffer protected by a ReentrantLock with separate notFull and notEmpty Condition queues (or two-lock split), always guarding await() inside a while loop.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Implement a Thread-Safe Bounded Blocking Queue experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Implement a Thread-Safe Bounded Blocking Queue: The problem: see what breaks without Naive Solution under real concurrency or scale.

Using synchronized (this) with if (count == items.length) wait(); and notify() has three fatal bugs: (1) if fails on spurious wakeups or when another producer steals the freed slot before the woken thread re-acquires the lock; (2) notify() cannot target consumers vs. producers, causing lost wakeups; (3) notifyAll() causes thundering-herd context switches across all 24 threads.

Lifecycle & Failure Recovery

Naive Solution (and Why It Breaks)

poll batchsink successpoison / timeoutAppended to LogLeased to ConsumerOffset CommittedMoved to DLQ
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Circular Ring Buffer + Dual Condition Queues.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Implement an ArrayBlockingQueue-style ring buffer with ReentrantLock and two Condition queues:

  • Fixed Ring Buffer (Object[capacity]): Maintain putIndex, takeIndex, and count modulo capacity for O(1) operations and zero node allocation; null out items[takeIndex] on dequeue so GC can collect consumed objects.
  • while Guard + Separate Conditions: Producers await() on notFull in a while (count == items.length) loop and call notEmpty.signal(); consumers await() on notEmpty in while (count == 0) and call notFull.signal().
  • Timed offer/poll & Backpressure: Use awaitNanos(nanos) for bounded waiting and shed excess ingress with HTTP 429 rather than blocking Netty event loops.
Backpressure & Signal Flow

Producer Blocking, Signal Handoff & Timed Shedding

Producer (16)ReentrantLockRing [N]Consumer (8)1. put(e): while(count==N)notFull.await2. take(): dequeue + null slot3. notFull.signal() wakes 1producer4. enqueue + notEmpty.signal()5. offer(50ms) timeout -> 429 shed

Targeted signal() wakes one waiting counterpart without thundering herds, while timed offer() enforces bounded backpressure.

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBlockingQueue<T> {
    private final Object[] items;
    private int putIndex, takeIndex, count;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();

    public BoundedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be > 0");
        this.items = new Object[capacity];
    }

    public void put(T item) throws InterruptedException {
        Objects.requireNonNull(item);
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                notFull.await();
            }
            enqueue(item);
        } finally {
            lock.unlock();
        }
    }

    public T take() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            while (count == 0) {
                notEmpty.await();
            }
            return dequeue();
        } finally {
            lock.unlock();
        }
    }

    public boolean offer(T item, long timeout, TimeUnit unit) throws InterruptedException {
        Objects.requireNonNull(item);
        long nanos = unit.toNanos(timeout);
        lock.lockInterruptibly();
        try {
            while (count == items.length) {
                if (nanos <= 0L) return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(item);
            return true;
        } finally {
            lock.unlock();
        }
    }

    private void enqueue(T item) {
        items[putIndex] = item;
        if (++putIndex == items.length) putIndex = 0;
        count++;
        notEmpty.signal();
    }

    @SuppressWarnings("unchecked")
    private T dequeue() {
        T item = (T) items[takeIndex];
        items[takeIndex] = null; // prevent GC retention
        if (++takeIndex == items.length) takeIndex = 0;
        count--;
        notFull.signal();
        return item;
    }
}

// Fail-fast backpressure with 429 shedding
if (!queue.offer(event, 50, TimeUnit.MILLISECONDS)) {
    metrics.counter("telemetry.dropped.backpressure").increment();
    return Response.status(429).build();
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Bounded Blocking Queues Apply in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Bounded ring buffers are the backbone of high-throughput in-process pipelines:

  • Log & Telemetry Shippers: Absorbs micro-bursts while applying backpressure (429) when disk/network sinks stall.
  • Thread Pool Work Queues: Bounds ThreadPoolExecutor queues instead of using unbounded LinkedBlockingQueue.
  • LMAX Disruptor / Two-Lock Queues: At >1M ops/sec, splitting takeLock and putLock (like LinkedBlockingQueue) or using lock-free CAS ring buffers eliminates producer-consumer contention.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must a bounded blocking queue check `while (count == items.length)` instead of `if (count == items.length)` before calling `await()`?

Recommended Learning Flow