Blocking queues compared
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every producer-consumer design needs a queue between the threads, and java.util.concurrent offers several. They differ in three ways that matter: how the items are stored, whether the queue has a size limit, and whether threads wait (block) or get an answer at once.
ArrayBlockingQueue versus LinkedBlockingQueue
A BlockingQueue is a thread-safe queue where put() waits when the queue is full and take() waits when it is empty, so producer threads and consumer threads can hand work over safely.
ArrayBlockingQueue stores items in a fixed array whose size you must give when you create it: new ArrayBlockingQueue<>(100). It uses one lock for both ends, so a producer and a consumer take turns.
Example 1 · The same order queue, two implementations
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;
public class TwoQueuesDemo { static final int POISON = -1; // "no more orders" marker
static long runPacking(BlockingQueue<Integer> orders) throws InterruptedException { long[] billTotal = new long[1]; Thread counter = new Thread(() -> { try { for (int bill = 1; bill <= 10_000; bill++) { orders.put(bill); } orders.put(POISON); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "order-counter"); Thread packer = new Thread(() -> { try { while (true) { int bill = orders.take(); if (bill == POISON) { break; } billTotal[0] += bill; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "packer"); counter.start(); packer.start(); counter.join(); packer.join(); return billTotal[0]; }
public static void main(String[] args) throws InterruptedException { BlockingQueue<Integer> array = new ArrayBlockingQueue<>(5); // capacity is required BlockingQueue<Integer> linked = new LinkedBlockingQueue<>(); // no capacity given
System.out.println("ArrayBlockingQueue free slots: " + array.remainingCapacity()); System.out.println("LinkedBlockingQueue free slots: " + linked.remainingCapacity()); System.out.println("Total with ArrayBlockingQueue: " + runPacking(array)); System.out.println("Total with LinkedBlockingQueue: " + runPacking(linked)); }}ArrayBlockingQueue free slots: 5 LinkedBlockingQueue free slots: 2147483647 Total with ArrayBlockingQueue: 50005000 Total with LinkedBlockingQueue: 50005000
What this code does
- The order counter puts 10,000 bills and a poison pill (
-1, a special "stop" item); the packer takes and adds them up. Both queues give the same total, because both implement the sameBlockingQueuemethods. remainingCapacity()shows the difference in limits: the array queue has 5 free slots, while the linked queue created without a capacity hasInteger.MAX_VALUE.
Its memory use is fixed from the start, and new ArrayBlockingQueue<>(100, true) makes waiting threads get served in arrival order (a fair queue, a little slower).
LinkedBlockingQueue stores each item in its own small node object. It has two locks, one for adding and one for removing, so a producer and a consumer can work at the same moment. The capacity is optional: new LinkedBlockingQueue<>(100) is bounded, but new LinkedBlockingQueue<>() allows Integer.MAX_VALUE items, which in practice means no limit.
Both support the same methods, and both give the same result in Example 1. Under heavy load from both sides, LinkedBlockingQueue often moves more items per second; ArrayBlockingQueue creates no garbage per item and has a fixed size. Measure on your own workload before choosing for speed.
put/take: wait until there is space / an item.offer/poll: return at once withfalse/nullinstead of waiting.offer(x, time, unit)/poll(time, unit): wait up to a time limit.add/remove: throw an exception instead (IllegalStateException: Queue full).
Bounded versus unbounded queues
Back-pressure means a full bounded queue makes producers wait, so a slow consumer slows the producers down to its own speed instead of letting work pile up without limit.
A bounded queue has a maximum size. When it is full, put makes the producer wait until a consumer takes something.
Example 2 · Back-pressure: bounded versus unbounded
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.LinkedBlockingQueue;
public class BoundedVersusUnboundedDemo { static volatile boolean open;
static int largestSize(BlockingQueue<String> queue) throws InterruptedException { open = true; int[] largest = new int[1]; Thread app = new Thread(() -> { int n = 0; try { while (open && n < 50_000) { queue.put("order-" + (++n)); // bounded: waits when full largest[0] = Math.max(largest[0], queue.size()); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "web-shop"); Thread paymentService = new Thread(() -> { try { while (open) { queue.take(); Thread.sleep(10); // slow: one order every 10 ms } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "paymentService");
app.start(); paymentService.start(); Thread.sleep(200); open = false; app.interrupt(); // wake the app if it is waiting in put() paymentService.interrupt(); app.join(); paymentService.join(); return largest[0]; }
public static void main(String[] args) throws InterruptedException { int bounded = largestSize(new ArrayBlockingQueue<>(10)); int unbounded = largestSize(new LinkedBlockingQueue<>()); System.out.println("Bounded queue (capacity 10) never above 10: " + (bounded <= 10)); System.out.println("Unbounded queue grew past 1,000 orders: " + (unbounded > 1_000)); }}Bounded queue (capacity 10) never above 10: true Unbounded queue grew past 1,000 orders: true
What this code does
- For about 200 ms the web shop adds orders as fast as it can, while the payment service takes one every 10 ms. With a capacity of 10,
putmakes the app wait, so the queue never holds more than 10 orders. - With no limit, the app never waits and thousands of orders pile up (the exact number changes from run to run; the program stops the app at 50,000 orders so it ends quickly). Left running, the pile would keep growing until memory runs out.
Example 3 · Rejecting work with offer and a timeout
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;
public class ServerBusyDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> payments = new ArrayBlockingQueue<>(3); // only 3 can wait
String[] requests = {"UPI-101", "UPI-102", "UPI-103", "UPI-104", "UPI-105"}; for (String r : requests) { // wait at most 50 ms for a free slot, then give up boolean accepted = payments.offer(r, 50, TimeUnit.MILLISECONDS); System.out.println(r + (accepted ? " queued" : " rejected: server busy, try again")); } System.out.println("Waiting in queue: " + payments); }}UPI-101 queued UPI-102 queued UPI-103 queued UPI-104 rejected: server busy, try again UPI-105 rejected: server busy, try again Waiting in queue: [UPI-101, UPI-102, UPI-103]
What this code does
- Only 3 payments may wait.
offer(r, 50, TimeUnit.MILLISECONDS)waits up to 50 ms for a free slot and returnsfalseif none appears. - No consumer runs here, so payments 4 and 5 are rejected after their 50 ms wait. The caller can then show "server busy" instead of hanging.
This is called back-pressure: a slow consumer automatically slows the producers down to its own speed, and the queue can never use more memory than its limit.
An unbounded queue never makes producers wait. If producers are faster than consumers for long enough, the queue keeps growing until the program runs out of memory (OutOfMemoryError). Example 2 shows a fast web shop feeding a slow payment service: the bounded queue stays at 10, the unbounded one runs away.
When waiting is not acceptable either, use offer with a timeout and reject the request, as a UPI server does with "server busy, try again" (Example 3). Failing fast with a clear message is better than accepting work the system can never finish.
Executors.newFixedThreadPool uses an unbounded LinkedBlockingQueue for its tasks. For a busy server, build a ThreadPoolExecutor with a bounded queue instead.PriorityBlockingQueue and DelayQueue in brief
PriorityBlockingQueue always hands out the smallest item first, by compareTo or by a Comparator you pass in. It is unbounded, so put never waits; take waits only when it is empty.
Example 4 · PriorityBlockingQueue: urgent tickets first
import java.util.Comparator;import java.util.concurrent.PriorityBlockingQueue;
record Ticket(String passenger, int priority) { } // 1 = most urgent
public class PriorityTicketsDemo { public static void main(String[] args) throws InterruptedException { PriorityBlockingQueue<Ticket> desk = new PriorityBlockingQueue<>( 11, Comparator.comparingInt(Ticket::priority));
Thread online = new Thread(() -> { desk.put(new Ticket("Rahul (general)", 3)); desk.put(new Ticket("Kamala (senior citizen)", 1)); }, "online-requests"); Thread station = new Thread(() -> { desk.put(new Ticket("Sneha (ladies quota)", 2)); desk.put(new Ticket("Vikram (waitlist)", 4)); desk.put(new Ticket("Dr. Iyer (emergency)", 0)); }, "station-requests"); online.start(); station.start(); online.join(); station.join();
while (!desk.isEmpty()) { Ticket t = desk.take(); // always the smallest priority first System.out.println("Serving " + t.passenger() + ", priority " + t.priority()); } }}Serving Dr. Iyer (emergency), priority 0 Serving Kamala (senior citizen), priority 1 Serving Sneha (ladies quota), priority 2 Serving Rahul (general), priority 3 Serving Vikram (waitlist), priority 4
What this code does
- Two threads add tickets in a mixed order.
takealways returns the ticket with the smallest priority number, so the emergency comes first and the waitlist last. - Every priority here is different on purpose: two tickets with the same priority could come out in either order.
Example 5 · DelayQueue: seat holds that expire
import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;
class SeatHold implements Delayed { final String seat; private final long expiresAt; // in System.nanoTime() units
SeatHold(String seat, long holdMillis) { this.seat = seat; this.expiresAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(holdMillis); }
@Override public long getDelay(TimeUnit unit) { // time left; 0 or less = expired return unit.convert(expiresAt - System.nanoTime(), TimeUnit.NANOSECONDS); }
@Override public int compareTo(Delayed other) { return Long.compare(getDelay(TimeUnit.NANOSECONDS), other.getDelay(TimeUnit.NANOSECONDS)); }}
public class SeatHoldExpiryDemo { public static void main(String[] args) throws InterruptedException { DelayQueue<SeatHold> holds = new DelayQueue<>(); holds.put(new SeatHold("E5", 150)); holds.put(new SeatHold("C2", 50)); holds.put(new SeatHold("D9", 100));
System.out.println("poll() right away: " + holds.poll()); for (int i = 0; i < 3; i++) { SeatHold h = holds.take(); // waits until the next hold expires System.out.println("Hold expired, seat " + h.seat + " is free again"); } }}poll() right away: null Hold expired, seat C2 is free again Hold expired, seat D9 is free again Hold expired, seat E5 is free again
What this code does
- Each
SeatHoldreports its remaining time throughgetDelay. Right after adding,poll()returnsnull, because no hold has expired yet. takewaits for the earliest expiry each time, so the seats come out as C2 (50 ms), D9 (100 ms), E5 (150 ms), whatever order they were added in.
Use it when urgent work must jump the line, like emergency quota tickets (Example 4). Items with equal priority come out in no fixed order, and its iterator does not show items in priority order.
DelayQueue holds items that implement Delayed, meaning each item says how long until it is ready. take waits until the item with the earliest deadline has expired; poll returns null if none has. It is useful for timeouts, such as releasing a cinema seat hold after a few minutes (Example 5).
ConcurrentLinkedQueue for non-blocking use
ConcurrentLinkedQueue is an unbounded, thread-safe queue that uses no locks at all: offer and poll are built on compare-and-set. It is non-blocking: poll on an empty queue returns null at once instead of waiting.
Example 6 · ConcurrentLinkedQueue: clicks with no blocking
import java.util.ArrayList;import java.util.List;import java.util.Queue;import java.util.concurrent.ConcurrentLinkedQueue;import java.util.concurrent.atomic.AtomicInteger;
public class NonBlockingQueueDemo { static volatile boolean producersDone = false;
public static void main(String[] args) throws InterruptedException { Queue<Integer> clicks = new ConcurrentLinkedQueue<>(); // lock-free, unbounded AtomicInteger processed = new AtomicInteger();
List<Thread> producers = new ArrayList<>(); for (int p = 0; p < 4; p++) { int first = p * 25_000; Thread t = new Thread(() -> { for (int id = first; id < first + 25_000; id++) { clicks.offer(id); } }, "web-" + (p + 1)); producers.add(t); }
List<Thread> workers = new ArrayList<>(); for (int w = 1; w <= 2; w++) { Thread t = new Thread(() -> { while (true) { boolean done = producersDone; // read the flag BEFORE polling Integer id = clicks.poll(); if (id != null) { processed.incrementAndGet(); } else if (done) { break; } else { Thread.onSpinWait(); // a real worker could do other work here } } }, "analytics-" + w); workers.add(t); }
for (Thread t : producers) t.start(); for (Thread t : workers) t.start(); for (Thread t : producers) t.join(); producersDone = true; for (Thread t : workers) t.join();
System.out.println("Clicks processed: " + processed.get()); System.out.println("Queue empty at the end: " + clicks.isEmpty()); }}Clicks processed: 100000 Queue empty at the end: true
What this code does
- Four producers add 100,000 click ids with
offer, and two workers remove them withpoll. Nothing ever blocks, and every click is processed exactly once. - A worker reads
producersDonebefore it polls. If the flag was already set and the queue is still empty, nothing more can arrive, so stopping is safe.Thread.onSpinWait()hints to the CPU that the thread is in a short polling loop.
It fits when consumers have other work to do and must not sleep on an empty queue, or when many threads add and remove at a very high rate, such as counting clicks for analytics (Example 6). It does not fit a classic producer-consumer: a consumer would have to keep polling in a loop, wasting CPU, and it has no limit. Its size() walks the whole queue and is only approximate under change; use isEmpty() for checks.
- Workers that must wait for jobs, with memory protection → bounded
ArrayBlockingQueueorLinkedBlockingQueue. - Urgent jobs first →
PriorityBlockingQueue. - Run something after a delay or timeout →
DelayQueue. - High-speed hand-off where nobody should block →
ConcurrentLinkedQueue.
Next step
Check your understanding
11 quick questions