Medium zalando java

What is a bounded blocking queue, and how do ArrayBlockingQueue, LinkedBlockingQueue and Semaphore compare?

The 30 second answer

A bounded blocking queue is a fixed-size buffer between producers and consumers. put waits when it's full and take waits when it's empty, so a fast producer slows to the consumer's pace instead of filling the heap. ArrayBlockingQueue is a circular array with one lock. LinkedBlockingQueue uses linked nodes with separate put and take locks. If you only need to cap concurrent work, a Semaphore is simpler.

Could you say this in an interview?

What it is and why it's used. The BlockingQueue Javadoc says implementations are designed primarily for producer-consumer queues, and Oracle's concurrency tutorial describes it as a first-in-first-out structure that blocks or times out when you add to a full queue or take from an empty one. "Bounded" means it has a fixed capacity. That capacity is the point: it caps the memory the backlog can use, and it turns "the consumer is slow" into "the producer waits", which is backpressure. Java Concurrency in Practice builds the same idea twice in its code listings: a producer-consumer file crawler on a BlockingQueue, and a hand-written BoundedBuffer that uses condition queues.

How ArrayBlockingQueue works inside. Its Javadoc calls it a classic "bounded buffer" whose capacity cannot change after creation. In the OpenJDK 21 source it is an Object[] items array used as a ring: putIndex and takeIndex move forward and wrap to 0 at the end. One ReentrantLock guards every operation, with two conditions on that lock, notFull for waiting producers and notEmpty for waiting consumers. It allocates nothing per element and has an optional fairness policy that hands the lock to the longest-waiting thread, at some cost in throughput.

How LinkedBlockingQueue works inside. Its Javadoc calls it optionally bounded. If you give no capacity, the bound is Integer.MAX_VALUE, which in practice means unbounded. The OpenJDK source describes it as a variant of the "two lock queue" algorithm. A putLock guards the tail and a takeLock guards the head, and an AtomicInteger count links them, so one producer and one consumer can work at the same time. The Javadoc's trade-off: linked queues typically have higher throughput than array-based queues but less predictable performance, partly because every element allocates a node.

Producer-consumer with put and take. The four method families behave differently on a full or empty queue:

  • Wait forever. put and take block until space or an element is available.
  • Wait with a deadline. offer(e, timeout, unit) and poll(timeout, unit) give up after a timeout, which is how you avoid a stuck thread.
  • Don't wait. offer(e) returns false and poll() returns null immediately.
  • Throw. add throws IllegalStateException when the queue is full.

To stop a consumer cleanly, send a "poison pill" value or interrupt it. A blocking call throws InterruptedException, and the handler should restore the interrupt flag.

Semaphore as a simpler alternative. The Semaphore Javadoc says semaphores are often used to restrict the number of threads that can access a resource. If you don't need to hand items from one thread to another, and you only want "at most N calls to the search cluster at once", acquire a permit before the call and release it in finally. That gives the same bound without a buffer. Java Concurrency in Practice's BoundedHashSet uses a semaphore the same way, to bound a collection.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class BoundedQueueDemo {
    static final String DONE = "DONE";   // "poison pill": tells the consumer to stop

    public static void main(String[] args) throws Exception {
        // 1) Producer-consumer with a bounded queue: capacity 3 = at most 3 waiting events in memory.
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 1; i <= 8; i++) {
                    long start = System.nanoTime();
                    queue.put("event-" + i);                        // blocks while the queue is full
                    long waitedMs = (System.nanoTime() - start) / 1_000_000;
                    System.out.println("put event-" + i + (waitedMs > 20 ? "  <- blocked: queue full, producer slowed down" : ""));
                }
                queue.put(DONE);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();                 // restore the flag, then exit
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    String event = queue.take();                    // blocks while the queue is empty
                    if (event.equals(DONE)) return;
                    Thread.sleep(100);                              // slow consumer, e.g. a bulk call to a search cluster
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
        producer.join();
        consumer.join();

        // 2) Semaphore alternative: no queue object, just "at most 2 calls in flight at once".
        Semaphore permits = new Semaphore(2);
        AtomicInteger inFlight = new AtomicInteger();
        AtomicInteger maxSeen = new AtomicInteger();
        ExecutorService pool = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            pool.submit(() -> {
                try {
                    permits.acquire();                              // blocks when 2 calls are already running
                    try {
                        int now = inFlight.incrementAndGet();
                        maxSeen.accumulateAndGet(now, Math::max);
                        Thread.sleep(50);                           // the protected call
                        inFlight.decrementAndGet();
                    } finally {
                        permits.release();                          // always give the permit back
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("max calls in flight = " + maxSeen.get());  // 2
    }
}

Verified with OpenJDK 21.0.13: the first four puts go straight in (three fill the queue and one replaces the item the consumer took), puts 5 to 8 block until the slow consumer makes room, and the semaphore part never has more than 2 calls in flight.

Bounded or unbounded. The ThreadPoolExecutor Javadoc states the trade-off directly. An unbounded queue, such as a LinkedBlockingQueue with no capacity, smooths out bursts but allows unbounded work queue growth when tasks arrive faster than they are processed. A bounded queue such as ArrayBlockingQueue helps prevent resource exhaustion but is harder to tune. Elasticsearch takes the bounded side. Its fixed thread pools set a bound on their queue by default, and when a bounded queue is full it rejects further work, which typically makes the request fail. The current docs size the search pool's queue at 1,000 times the pool size.

  • Use a bounded queue when producers can outrun consumers: ingestion, indexing, calls to a shared cluster. Choose what happens when it's full (block, time out, reject, or drop) and monitor the queue depth.
  • Use an unbounded queue only when the input itself is bounded or tiny, such as a fixed batch you enqueue once, or when something upstream already limits the rate.
  • Size the bound from the numbers. The bound equals how many items you can afford to hold in memory, and how long the newest item may wait, which is roughly the queue length divided by the consumer rate. Bigger is not safer: a huge queue just hides overload until latency or the heap explodes.

Alternate interview scenarios

"Your indexing service runs out of memory during a traffic spike, and the heap dump is full of queued events. What changed?"

Probably an unbounded queue, such as a LinkedBlockingQueue with no capacity or Executors.newFixedThreadPool, which uses one. Give it a capacity, decide the full-queue policy, and add metrics for depth and rejections.

"Why not just make the queue very large?"

A large queue converts overload into latency: each item waits behind everything ahead of it, and on a crash you lose everything in memory. Backpressure only works if the bound is small enough for the producer to feel it.

Sources (15)
  1. BlockingQueue Javadoc (Java 21)docs.oracle.com
  2. ArrayBlockingQueue Javadoc (Java 21): classic bounded buffer, fairnessdocs.oracle.com
  3. LinkedBlockingQueue Javadoc (Java 21): optionally bounded, throughput trade-offdocs.oracle.com
  4. OpenJDK 21 source: ArrayBlockingQueue (one lock, notEmpty and notFull)github.com
  5. OpenJDK 21 source: LinkedBlockingQueue (two lock queue, putLock and takeLock)github.com
  6. Semaphore Javadoc (Java 21)docs.oracle.com
  7. Executors Javadoc (Java 21): newFixedThreadPool uses a shared unbounded queuedocs.oracle.com
  8. ThreadPoolExecutor Javadoc (Java 21): unbounded versus bounded queuesdocs.oracle.com
  9. Oracle Java tutorial: Concurrent collectionsdocs.oracle.com
  10. Oracle Java tutorial: Guarded blocks (producer-consumer)docs.oracle.com
  11. Java Concurrency in Practice listing: ProducerConsumerjcip.net
  12. Java Concurrency in Practice listing: BoundedBufferjcip.net
  13. Java Concurrency in Practice listing: BoundedHashSet (Semaphore)jcip.net
  14. Elasticsearch docs: Thread pool settings (bounded queues and rejection)elastic.co
  15. Zalando Engineering: Back-pressure strategy for a sharded Akka cluster (2019)engineering.zalando.com