BlockingQueue
How Java's BlockingQueue interface passes items safely between threads, and how its implementations differ: size limits, ordering, delays and direct hand-over.
Contents
Introduction put() and take() Bounded and unbounded queues Stopping a consumer Taking items in batches with drainTo PriorityBlockingQueue: most urgent item first DelayQueue: items that become ready later SynchronousQueue and LinkedTransferQueue: direct hand-over The four ways to call each operation How it works inside Recap
Introduction
BlockingQueuejava.util.concurrent
BlockingQueueput(item)take()
Because BlockingQueue
Look at the picture. The producer thread puts items into the queue, and the consumer thread takes them out, oldest first. This queue has room for three items and all three places are taken, so item 4 cannot go in yet: the producer's put()take()
The examples on this page were run with Java 25.
put() and take()
put(item)take()
The simplest implementation to start with is ArrayBlockingQueueArrayBlockingQueue
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3); // room for 3 items
queue.put(item); // producer: waits while the queue is full
queue.take(); // consumer: waits while the queue is empty
The full program prints the time at which each item went into the queue:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class PutAndTake {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(3); // room for 3 items
List<Integer> consumed = new ArrayList<>();
// the consumer: takes one item every 200 ms
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 6; i++) {
Thread.sleep(200); // busy for 200 ms before each item
consumed.add(queue.take()); // then take the next item
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumer.start();
// the producer (here, the main thread): puts 6 items as fast as it can
long start = System.nanoTime();
for (int item = 1; item <= 6; item++) {
queue.put(item); // waits while the queue is full
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("item " + item + " went into the queue after "
+ Math.round(ms / 100.0) * 100 + " ms");
}
consumer.join(); // wait until all 6 are taken
System.out.println("taken, in this order: " + consumed);
}
}
Running it prints:
item 1 went into the queue after 0 ms
item 2 went into the queue after 0 ms
item 3 went into the queue after 0 ms
item 4 went into the queue after 200 ms
item 5 went into the queue after 400 ms
item 6 went into the queue after 600 ms
taken, in this order: [1, 2, 3, 4, 5, 6]
Look at the first three lines. Items 1, 2 and 3 went in straight away, because the queue had room for three. Now look at item 4: it went in only after 200 ms. The queue was full, so put()
The last line shows that the items were taken in the order they were put in. An ArrayBlockingQueue
Notice what the program does not contain: no lock, no synchronizedwait()notify()
Bounded and unbounded queues
A bounded queue has a maximum size, like the ArrayBlockingQueueput()
LinkedBlockingQueue
The example below adds items with offer()put()offer(item)LinkedBlockingQueueArrayBlockingQueue
new LinkedBlockingQueue<>() // no size given: unbounded
new ArrayBlockingQueue<>(10_000) // bounded: room for 10,000 items
queue.offer(item) // true if added, false at once if the queue is full
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class BoundedAndUnbounded {
public static void main(String[] args) {
int items = 2000000; // the consumer is not taking anything
BlockingQueue<Integer> unbounded = new LinkedBlockingQueue<>(); // no size given
long before = usedHeap();
int accepted = 0;
for (int i = 1; i <= items; i++) {
if (unbounded.offer(i)) { // offer: add if there is room, never wait
accepted++;
}
}
long grownMb = (usedHeap() - before) / 1000000;
System.out.printf("unbounded: accepted %,d items, memory grew by about %d MB%n",
accepted, Math.round(grownMb / 10.0) * 10);
unbounded.clear();
BlockingQueue<Integer> bounded = new ArrayBlockingQueue<>(10000);
int rejected = 0;
for (int i = 1; i <= items; i++) {
if (!bounded.offer(i)) {
rejected++; // the producer finds out at once
}
}
System.out.printf("bounded: accepted %,d items, rejected %,d%n",
bounded.size(), rejected);
}
static long usedHeap() {
System.gc();
Runtime rt = Runtime.getRuntime();
return rt.totalMemory() - rt.freeMemory();
}
}
Running it prints:
unbounded: accepted 2,000,000 items, memory grew by about 80 MB
bounded: accepted 10,000 items, rejected 1,990,000
Look at the first line. The unbounded queue accepted all two million items, and memory grew by about 80 MB. That is about 40 bytes per item: a 24-byte list entry plus a 16-byte IntegerOutOfMemoryError
Now look at the second line. The bounded queue accepted 10,000 items and refused the other 1,990,000, and each refusal told the producer at once that the consumer was behind. The producer can then react: wait, slow down, report an error to its caller, or drop work that does not matter. With an unbounded queue, it gets no such signal.
"Unbounded" is not quite exact. A LinkedBlockingQueueInteger.MAX_VALUEExecutors.newFixedThreadPool
Stopping a consumer
A consumer usually runs in a loop that calls take()take()
A stop item (poison pill)
A poison pill is a special item that means "stop", put into the queue after the last real item. A consumer that takes it leaves its loop. Because the queue hands out items in order, every item put in before the pill is taken before it. Consider the following example, where three consumers share one queue, and the producer puts in 1,000 tasks followed by one pill for each consumer:
static final Task STOP = new Task(-1); // the poison pill
Task task = queue.take();
if (task == STOP) {
return; // stop consuming
}
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class PoisonPill {
record Task(int id) { }
static final Task STOP = new Task(-1); // the poison pill
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Task> queue = new ArrayBlockingQueue<>(10);
AtomicInteger processed = new AtomicInteger();
Thread[] consumers = new Thread[3];
for (int c = 0; c < consumers.length; c++) {
consumers[c] = new Thread(() -> {
try {
while (true) {
Task task = queue.take();
if (task == STOP) {
return; // the pill: stop consuming
}
processed.incrementAndGet();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumers[c].start();
}
// the producer: 1,000 tasks, then one pill per consumer
for (int id = 1; id <= 1000; id++) {
queue.put(new Task(id));
}
for (int c = 0; c < consumers.length; c++) {
queue.put(STOP);
}
for (Thread consumer : consumers) {
consumer.join(); // returns once that consumer has stopped
}
System.out.println("tasks processed: " + processed.get());
System.out.println("items left in the queue: " + queue.size());
}
}
Running it prints:
tasks processed: 1000
items left in the queue: 0
Look at the output: all 1,000 tasks were processed and nothing was left in the queue. Which consumer processed which task changes from run to run, which is why the program only counts them.
Two details matter. The producer puts one pill per consumer, because each consumer takes exactly one and stops; with a single pill, two of the three consumers would wait forever. And the check uses ==
Interrupt
The other way is to call interrupt()take()put()InterruptedExceptiontake()
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class InterruptConsumer {
public static void main(String[] args) throws InterruptedException {
// 1. a consumer waiting on an empty queue
BlockingQueue<Integer> empty = new ArrayBlockingQueue<>(10);
Thread consumer = new Thread(() -> {
try {
empty.take(); // nothing to take: waits
} catch (InterruptedException e) {
System.out.println("waiting consumer: take() threw InterruptedException");
}
});
consumer.start();
Thread.sleep(200);
consumer.interrupt();
consumer.join();
// 2. a thread that is already interrupted, with items still in the queue
BlockingQueue<Integer> full = new ArrayBlockingQueue<>(10);
full.put(1);
full.put(2);
full.put(3);
Thread.currentThread().interrupt(); // interrupt the main thread itself
try {
full.take();
} catch (InterruptedException e) {
System.out.println("interrupted thread: take() threw at once; items left: "
+ full.size());
}
}
}
Running it prints:
waiting consumer: take() threw InterruptedException
interrupted thread: take() threw at once; items left: 3
Look at the first line: the waiting consumer woke up with an InterruptedExceptiontake()
So the two ways suit different needs. A poison pill lets the consumer finish every item that was queued before it. An interrupt stops the consumer quickly, but may leave items in the queue; if they matter, the consumer can save them in its catch
Taking items in batches with drainTo
drainTo(collection, max)maxtake()
batch.add(queue.take()); // wait for at least one item
queue.drainTo(batch, 9); // then take up to 9 more, without waiting
Consider the following example, where 25 items are already waiting and the consumer handles them in batches of up to 10. The main thread stops the consumer with interrupt()
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class DrainToBatches {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
for (int item = 1; item <= 25; item++) {
queue.put(item); // 25 items are already waiting
}
Thread consumer = new Thread(() -> {
List<Integer> batch = new ArrayList<>();
try {
while (true) {
batch.add(queue.take()); // wait for at least one item
queue.drainTo(batch, 9); // then take up to 9 more, without waiting
System.out.println("batch of " + batch.size() + ": items "
+ batch.get(0) + " to " + batch.get(batch.size() - 1));
batch.clear();
}
} catch (InterruptedException e) {
System.out.println("consumer stopped; items left: " + queue.size());
}
});
consumer.start();
Thread.sleep(300); // by now all 25 are taken
consumer.interrupt();
consumer.join();
}
}
Running it prints:
batch of 10: items 1 to 10
batch of 10: items 11 to 20
batch of 5: items 21 to 25
consumer stopped; items left: 0
Look at the first three lines: batches of 10, 10 and 5. take()drainTo()
drainTo()poll()
PriorityBlockingQueue: most urgent item first
The queues so far hand out the oldest item first. A PriorityBlockingQueueComparator
new PriorityBlockingQueue<>(11, Comparator.comparingInt(Task::priority)) // lowest number first
The 11 is only the starting size of the queue's internal array; the queue grows as needed. Consider the following example, where five tasks are put in with priorities 3, 3, 1, 2 and 3, and priority 1 is the most urgent:
import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;
public class PriorityQueueDemo {
record Task(int id, int priority) { } // priority 1 is the most urgent
public static void main(String[] args) throws InterruptedException {
PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>(11,
Comparator.comparingInt(Task::priority));
queue.put(new Task(1, 3));
queue.put(new Task(2, 3));
queue.put(new Task(3, 1));
queue.put(new Task(4, 2));
queue.put(new Task(5, 3));
while (!queue.isEmpty()) {
Task task = queue.take();
System.out.println("task " + task.id() + " (priority " + task.priority() + ")");
}
}
}
Running it prints:
task 3 (priority 1)
task 4 (priority 2)
task 2 (priority 3)
task 1 (priority 3)
task 5 (priority 3)
Look at the first two lines. Task 3, with priority 1, came out first, and task 4, with priority 2, came out second, even though they were put in third and fourth.
Now look at the last three lines. Tasks 1, 2 and 5 all have priority 3, and they came out as 2, 1, 5, not in the order they were put in. For items that compare as equal, the queue makes no promise about order. If equal items must keep their arrival order, give each item a sequence number when it is created and compare on that number when the priorities are equal.
A PriorityBlockingQueueput()
DelayQueue: items that become ready later
A DelayQueuetake()
An item in a DelayQueueDelayedgetDelay()compareTo()
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class DelayQueueDemo {
record DelayedTask(int id, long readyAtNanos) implements Delayed {
@Override
public long getDelay(TimeUnit unit) { // how long until this task is ready
return unit.convert(readyAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed other) { // the task ready soonest comes first
return Long.compare(getDelay(TimeUnit.NANOSECONDS),
other.getDelay(TimeUnit.NANOSECONDS));
}
}
public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayedTask> queue = new DelayQueue<>();
long start = System.nanoTime();
queue.put(new DelayedTask(1, start + TimeUnit.MILLISECONDS.toNanos(300)));
queue.put(new DelayedTask(2, start + TimeUnit.MILLISECONDS.toNanos(100)));
System.out.println("poll() right away: " + queue.poll()
+ " (the queue holds " + queue.size() + ")");
for (int i = 0; i < 2; i++) {
DelayedTask task = queue.take(); // waits until the next task is ready
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("after about " + Math.round(ms / 100.0) * 100
+ " ms: task " + task.id());
}
}
}
Running it prints:
poll() right away: null (the queue holds 2)
after about 100 ms: task 2
after about 300 ms: task 1
Look at the first line: poll()take()
A DelayQueueScheduledExecutorService
SynchronousQueue and LinkedTransferQueue: direct hand-over
The queues so far store items until a consumer is ready. A SynchronousQueueput()take()LinkedTransferQueuetransfer()tryTransfer()
Consider the following example, where the consumer only arrives after 200 ms:
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.atomic.AtomicInteger;
public class DirectHandOff {
public static void main(String[] args) throws InterruptedException {
SynchronousQueue<Integer> handOff = new SynchronousQueue<>();
System.out.println("offer(1), no consumer waiting: " + handOff.offer(1));
AtomicInteger taken = new AtomicInteger();
Thread consumer = new Thread(() -> {
try {
Thread.sleep(200); // the consumer arrives after 200 ms
taken.set(handOff.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
consumer.start();
long start = System.nanoTime();
handOff.put(2); // waits until the consumer takes it
long ms = (System.nanoTime() - start) / 1000000;
consumer.join();
System.out.println("put(2) returned after about " + Math.round(ms / 100.0) * 100
+ " ms; the consumer took " + taken.get());
LinkedTransferQueue<Integer> transfer = new LinkedTransferQueue<>();
transfer.put(3); // stored like any queue, never waits
boolean handedOver = transfer.tryTransfer(4); // only if a consumer is waiting
System.out.println("tryTransfer(4), no consumer waiting: " + handedOver);
System.out.println("items in the LinkedTransferQueue: " + transfer);
}
}
Running it prints:
offer(1), no consumer waiting: false
put(2) returned after about 200 ms; the consumer took 2
tryTransfer(4), no consumer waiting: false
items in the LinkedTransferQueue: [3]
Look at the first line: offer(1)SynchronousQueueput(2)
Executors.newCachedThreadPool()
The last two lines are the LinkedTransferQueueput(3)tryTransfer(4)
Because every item needs both threads to meet, a SynchronousQueue
The four ways to call each operation
put()take()offer()ArrayBlockingQueue
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
public class FourWays {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1); // room for one item
queue.put(1); // now it is full
try {
queue.add(2);
} catch (IllegalStateException e) {
System.out.println("add(2), queue full: throws IllegalStateException");
}
System.out.println("offer(2), queue full: returns " + queue.offer(2));
long start = System.nanoTime();
boolean added = queue.offer(2, 200, TimeUnit.MILLISECONDS);
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("offer(2, 200 ms), queue full: returns " + added
+ " after about " + Math.round(ms / 100.0) * 100 + " ms");
queue.take(); // now it is empty
System.out.println("poll(), queue empty: returns " + queue.poll());
try {
queue.offer(null);
} catch (NullPointerException e) {
System.out.println("offer(null): throws NullPointerException");
}
}
}
Running it prints:
add(2), queue full: throws IllegalStateException
offer(2), queue full: returns false
offer(2, 200 ms), queue full: returns false after about 200 ms
poll(), queue empty: returns null
offer(null): throws NullPointerException
Look at the first three lines, on the full queue: add()offer()offer()poll()poll()
The table lists the whole set:
| Operation | Throws | Returns a special value | Waits | Waits up to a time |
|---|---|---|---|---|
| Add | add(e) | offer(e) | put(e) | offer(e, time, unit) |
| Remove | remove() | poll() | take() | poll(time, unit) |
| Look at the next item | element() | peek() | None | None |
add()remove()element()BlockingQueueCollectionput()take()offer()poll()
How it works inside
An ArrayBlockingQueueReentrantLocknotEmptynotFulltake()notEmptynotFullput()put()LinkedBlockingQueue
The queue also makes the item itself safe to read. The BlockingQueuevolatile
Recap
One implementation did not appear above: LinkedBlockingDeque
| Class | Since | Limit | Order | Good for |
|---|---|---|---|---|
ArrayBlockingQueue | Java 5 | Fixed, set when created | Oldest first | Producer-consumer with predictable memory |
LinkedBlockingQueue | Java 5 | Optional; without one, Integer.MAX_VALUE | Oldest first | Producer-consumer where both sides run hard |
LinkedBlockingDeque | Java 6 | Optional | Either end | Putting items back at the front |
PriorityBlockingQueue | Java 5 | None | By your comparison | Urgent items first |
DelayQueue | Java 5 | None | By ready time | Retries, timeouts, delayed work |
SynchronousQueue | Java 5 | Holds nothing | Direct hand-over | Making the producer wait for a consumer |
LinkedTransferQueue | Java 7 | None | Oldest first | Queueing that can also hand over directly |
| Situation | Use |
|---|---|
| Passing items between threads | ArrayBlockingQueueLinkedBlockingQueue |
| Some items are more urgent | PriorityBlockingQueue |
| Items become ready at a set time | DelayQueueScheduledExecutorService |
| Each item goes straight to a waiting consumer | SynchronousQueue |
| Handling items in batches | Wait with take()drainTo() |
| Stopping consumers after all items are handled | One poison pill per consumer |
| Stopping consumers quickly | interrupt() |
If the work is tasks rather than data, an