Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
Coordinate Java threads without explicit locks: BlockingQueue put and take, offer and poll with timeouts, ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, TransferQueue, DelayQueue, poison pills, ConcurrentSkipListMap and weakly consistent iterators.
kvi5hnuCode Sprout team member11 min readOn this page
If several threads modify an ordinary data structure at the same time, they can wreck it. One thread may be halfway through relinking a hash table's buckets when another follows the half-updated links, and the result can be an exception, lost entries or an infinite loop. You could protect every collection with your own lock, but it's usually far easier to use a collection that is built for concurrency. This article covers blocking queues, which are the most useful tool for coordinating threads, and the efficient concurrent maps, sets and queues of java.util.concurrent.
Blocking queues
Many threading problems can be formulated as a producer–consumer pipeline. Producer threads insert items into a queue, and consumer threads remove them. The queue safely hands each item from one thread to another. In the bank example, transfer threads could insert transfer instructions into a queue, and a single thread could carry them out. Only that thread would touch the bank's internals, so no synchronization of your own is needed. The queue's authors dealt with the locks and conditions so that you don't have to.
A blocking queue makes a thread wait when it adds to a full queue or removes from an empty one. That makes the queue a natural load balancer. If producers are slower, consumers block until results arrive. If producers are faster, the queue fills up and producers block until consumers catch up. A bounded queue therefore also provides backpressure, so a fast producer can't fill all of memory.

The three method families
BlockingQueue methods come in three groups. They do the same thing normally and differ only in what happens when the queue is full or empty:
| Method | Normal action | When full / empty |
|---|---|---|
add(e) | adds an element | throws IllegalStateException if full |
remove() | removes and returns the head | throws NoSuchElementException if empty |
element() | returns the head | throws NoSuchElementException if empty |
offer(e) | adds an element, returns true | returns false if full |
poll() | removes and returns the head | returns null if empty |
peek() | returns the head | returns null if empty |
put(e) | adds an element | blocks until there is room |
take() | removes and returns the head | blocks until an element is available |
How to choose:
- When the queue is a thread coordination tool, use
putandtake. - The exception-throwing methods rarely make sense across threads, since the queue can become full or empty at any moment. When you don't want to block, use
offer,pollandpeek, which return a failure value instead. offerandpollalso have timed versions that give up after a while:
boolean success = q.offer(x, 100, TimeUnit.MILLISECONDS); // false if still full after 100 ms
Object head = q.poll(100, TimeUnit.MILLISECONDS); // null if still empty
put and take are the equivalents of offer and poll without a timeout. Because poll and peek use null to signal failure, you can't insert null into these queues. Attempting it throws NullPointerException. drainTo(collection) removes all available elements at once, and remainingCapacity() reports the free space.
The implementations
ArrayBlockingQueueis bounded, with a fixed capacity, and backed by a circular array. The optionalfairflag gives the longest-waiting threads priority. Fairness costs significant throughput, so use it only when the problem demands it.LinkedBlockingQueueis backed by a linked list and is unbounded by default (Integer.MAX_VALUE). Pass a capacity to bound it. It uses separate locks for the head and tail, so producers and consumers contend less.LinkedBlockingDequeis the double-ended version, withputFirst,putLast,takeFirst,takeLastand their timedoffer/pollvariants. It's useful for work stealing.PriorityBlockingQueueis an unbounded priority heap, not FIFO. Elements come out in priority order, which is either natural ordering or aComparator. Retrieval blocks when it is empty. Its default initial capacity is 11.DelayQueueholds elements that implementDelayed. An element can be taken only after its delay has expired, and the one that expires soonest comes out first. It's useful for timeouts and simple scheduling.TransferQueue(implemented byLinkedTransferQueue) lets a producer wait until a consumer has received the item.transfer(item)blocks until another thread takes it.tryTransfer(item)succeeds only if a consumer is already waiting, andtryTransfer(item, time, unit)waits up to the timeout.SynchronousQueuehas no capacity at all. Eachputwaits for a matchingtake, like a direct handoff.Executors.newCachedThreadPooluses one internally.
Ending consumers with a poison pill
How do consumers know the work is finished? A common trick is to enqueue a special termination object, often called a poison pill. It's like a dummy suitcase labeled "last bag" on a baggage carousel. The producer puts it after the last real item. A consumer that takes it puts it back for the others and exits, so all consumers stop:
Doc d = queue.take();
if (d == DONE) {
queue.put(d); // let the other consumers see it too
break;
}
search(d);
A classic example searches a directory tree for a keyword. One producer thread enumerates files into a bounded queue, which is fast and would flood memory if the queue were unbounded, and many searcher threads take files and print the matching lines. Our demo does the same with in-memory documents. Notice that neither side contains synchronized, a lock or a condition. The queue is the synchronization mechanism. Alternatives to poison pills are interrupting the consumers, or using an ExecutorService, whose close() waits for the submitted tasks.
Efficient maps, sets and queues
For shared collections that aren't used for handoff, java.util.concurrent provides:
ConcurrentHashMap, a hash map that many threads can read and update at once (details in article 101).ConcurrentSkipListMapandConcurrentSkipListSet, sorted and navigable (headMap,ceilingKey,pollFirst, …). They are the concurrent counterparts ofTreeMapandTreeSet, built on skip lists instead of red-black trees.ConcurrentLinkedQueueandConcurrentLinkedDeque, unbounded non-blocking queues using lock-free algorithms. Use them when threads should never wait.
These classes use sophisticated algorithms that let threads work on different parts of the structure at the same time, which minimizes contention. Three behaviors differ from the ordinary collections:
size()isn't necessarily constant time, and under concurrent updates it's only an estimate. A hugeConcurrentHashMapcan hold more than 2³¹ entries, somappingCount()returns the count as along.- Iterators are weakly consistent. They may or may not reflect changes made after they were created, but they never return an element twice and never throw
ConcurrentModificationException. Ordinaryjava.utilcollections throw that exception when modified during iteration. nullis not allowed as a key, value or element, becausenullis used to signal "absent".
ConcurrentHashMap lets any number of readers proceed without locking, and a writer locks only the single bin it updates, so threads updating different keys rarely block each other. Like HashMap since Java 8, it turns overcrowded buckets into balanced trees when keys are Comparable. That keeps lookups at O(log n) even when an attacker crafts many keys with the same hash code.
A complete example
The demo runs a keyword search with one producer, four consumers and a poison pill. It shows each method family on a full and an empty ArrayBlockingQueue, a put that blocks until a take makes room, and the other blocking queues: LinkedBlockingDeque, PriorityBlockingQueue, LinkedTransferQueue, SynchronousQueue and DelayQueue. It then uses ConcurrentSkipListMap/Set and ConcurrentLinkedQueue, and compares a weakly consistent iterator with a fail-fast one.
import java.util.*;
import java.util.concurrent.*;
public class Solution {
record Doc(String name, List<String> lines) {}
private static final Doc DONE = new Doc("<done>", List.of()); // poison pill
public static void main(String[] args) throws Exception {
System.out.println("-- producer/consumer keyword search --");
var docs = new ArrayList<Doc>();
for (int i = 1; i <= 30; i++) {
var lines = new ArrayList<String>();
for (int j = 1; j <= 5; j++)
lines.add((i * j) % 7 == 0 ? "uses volatile here" : "plain line " + j);
docs.add(new Doc(String.format("File%02d.java", i), lines));
}
BlockingQueue<Doc> queue = new ArrayBlockingQueue<>(5);
var matches = new ConcurrentLinkedQueue<String>();
Thread producer = Thread.ofPlatform().start(() -> {
try {
for (Doc d : docs) queue.put(d); // blocks while the queue is full
queue.put(DONE);
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
var searchers = new ArrayList<Thread>();
for (int i = 0; i < 4; i++)
searchers.add(Thread.ofPlatform().start(() -> {
try {
while (true) {
Doc d = queue.take(); // blocks while the queue is empty
if (d == DONE) { queue.put(d); break; } // put it back for the others
for (int n = 0; n < d.lines().size(); n++)
if (d.lines().get(n).contains("volatile"))
matches.add(d.name() + ":" + (n + 1));
}
} catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}));
producer.join();
for (Thread t : searchers) t.join();
var sorted = new ArrayList<>(matches);
Collections.sort(sorted);
System.out.println(" " + sorted.size() + " matches: " + sorted.subList(0, 6) + " ...");
System.out.println("-- the three method families on a full/empty queue --");
var q = new ArrayBlockingQueue<String>(2);
q.add("a"); q.add("b");
try { q.add("c"); } catch (IllegalStateException e) { System.out.println(" add on full: IllegalStateException"); }
System.out.println(" offer on full: " + q.offer("c"));
System.out.println(" offer with 50 ms timeout: " + q.offer("c", 50, TimeUnit.MILLISECONDS));
System.out.println(" peek: " + q.peek() + ", poll: " + q.poll() + ", remove: " + q.remove());
System.out.println(" poll on empty: " + q.poll() + ", peek on empty: " + q.peek());
try { q.element(); } catch (NoSuchElementException e) { System.out.println(" element on empty: NoSuchElementException"); }
try { q.remove(); } catch (NoSuchElementException e) { System.out.println(" remove on empty: NoSuchElementException"); }
System.out.println(" poll with 50 ms timeout: " + q.poll(50, TimeUnit.MILLISECONDS));
try { q.offer(null); } catch (NullPointerException e) { System.out.println(" null elements: NullPointerException"); }
System.out.println(" remainingCapacity: " + q.remainingCapacity());
System.out.println("-- put blocks until there is room --");
var tiny = new ArrayBlockingQueue<Integer>(1);
tiny.put(1);
Thread blockedPutter = Thread.ofPlatform().start(() -> {
try { tiny.put(2); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
waitForState(blockedPutter, Thread.State.WAITING);
System.out.println(" putter state: " + blockedPutter.getState());
System.out.println(" take: " + tiny.take());
blockedPutter.join();
System.out.println(" putter finished, queue now " + tiny);
System.out.println("-- other blocking queues --");
var deque = new LinkedBlockingDeque<String>(3);
deque.putLast("middle"); deque.putFirst("front"); deque.putLast("back");
System.out.println(" LinkedBlockingDeque: " + deque + ", takeLast: " + deque.takeLast());
var pq = new PriorityBlockingQueue<Integer>(11, Comparator.reverseOrder());
pq.addAll(List.of(5, 1, 9, 3));
var drained = new ArrayList<Integer>();
pq.drainTo(drained);
System.out.println(" PriorityBlockingQueue (largest first) drained: " + drained);
var tq = new LinkedTransferQueue<String>();
Thread transferer = Thread.ofPlatform().start(() -> {
try { tq.transfer("parcel"); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
waitForState(transferer, Thread.State.WAITING);
System.out.println(" transfer() waits for a consumer: " + transferer.getState());
System.out.println(" consumer takes: " + tq.take());
transferer.join();
System.out.println(" tryTransfer with no consumer: " + tq.tryTransfer("x") + ", queue size " + tq.size());
var sync = new SynchronousQueue<String>();
System.out.println(" SynchronousQueue offer with no taker: " + sync.offer("hello") + ", size " + sync.size());
record Delayed1(String name, long readyAt) implements Delayed {
public long getDelay(TimeUnit unit) { return unit.convert(readyAt - System.nanoTime(), TimeUnit.NANOSECONDS); }
public int compareTo(Delayed o) { return Long.compare(getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS)); }
}
var dq = new DelayQueue<Delayed1>();
long now = System.nanoTime();
dq.put(new Delayed1("later", now + TimeUnit.MILLISECONDS.toNanos(60)));
dq.put(new Delayed1("sooner", now + TimeUnit.MILLISECONDS.toNanos(20)));
System.out.println(" DelayQueue poll right away: " + dq.poll());
System.out.println(" DelayQueue take: " + dq.take().name() + ", then " + dq.take().name());
System.out.println("-- efficient concurrent collections --");
var skip = new ConcurrentSkipListMap<String, Integer>();
var workers = new ArrayList<Callable<Void>>();
String[] words = {"pear", "apple", "fig", "kiwi", "banana", "cherry", "date", "grape"};
for (String w : words) workers.add(() -> { skip.put(w, w.length()); return null; });
try (var pool = Executors.newFixedThreadPool(4)) { pool.invokeAll(workers); }
System.out.println(" ConcurrentSkipListMap (sorted): " + skip);
System.out.println(" headMap(\"date\"): " + skip.headMap("date") + ", ceilingKey(\"c\"): " + skip.ceilingKey("c"));
var set = new ConcurrentSkipListSet<>(List.of(40, 10, 30, 20));
System.out.println(" ConcurrentSkipListSet: " + set + ", pollFirst: " + set.pollFirst());
var clq = new ConcurrentLinkedQueue<>(List.of("x", "y"));
clq.offer("z");
System.out.println(" ConcurrentLinkedQueue poll: " + clq.poll() + ", remaining " + clq);
System.out.println("-- weakly consistent iterators --");
var chm = new ConcurrentHashMap<String, Integer>(Map.of("a", 1, "b", 2, "c", 3));
int seen = 0;
for (String k : chm.keySet()) { chm.put(k.toUpperCase(), 0); seen++; }
System.out.println(" modified a ConcurrentHashMap while iterating: no exception, size now " + chm.size()
+ ", mappingCount " + chm.mappingCount() + ", visited >= 3: " + (seen >= 3));
var hm = new HashMap<String, Integer>(Map.of("a", 1, "b", 2, "c", 3));
try {
for (String k : hm.keySet()) hm.put(k + k, 0);
} catch (ConcurrentModificationException e) {
System.out.println(" same with a HashMap: ConcurrentModificationException");
}
}
static void waitForState(Thread t, Thread.State s) throws InterruptedException {
while (t.getState() != s) Thread.sleep(5);
}
}
-- producer/consumer keyword search --
20 matches: [File07.java:1, File07.java:2, File07.java:3, File07.java:4, File07.java:5, File14.java:1] ...
-- the three method families on a full/empty queue --
add on full: IllegalStateException
offer on full: false
offer with 50 ms timeout: false
peek: a, poll: a, remove: b
poll on empty: null, peek on empty: null
element on empty: NoSuchElementException
remove on empty: NoSuchElementException
poll with 50 ms timeout: null
null elements: NullPointerException
remainingCapacity: 2
-- put blocks until there is room --
putter state: WAITING
take: 1
putter finished, queue now [2]
-- other blocking queues --
LinkedBlockingDeque: [front, middle, back], takeLast: back
PriorityBlockingQueue (largest first) drained: [9, 5, 3, 1]
transfer() waits for a consumer: WAITING
consumer takes: parcel
tryTransfer with no consumer: false, queue size 0
SynchronousQueue offer with no taker: false, size 0
DelayQueue poll right away: null
DelayQueue take: sooner, then later
-- efficient concurrent collections --
ConcurrentSkipListMap (sorted): {apple=5, banana=6, cherry=6, date=4, fig=3, grape=5, kiwi=4, pear=4}
headMap("date"): {apple=5, banana=6, cherry=6}, ceilingKey("c"): cherry
ConcurrentSkipListSet: [10, 20, 30, 40], pollFirst: 10
ConcurrentLinkedQueue poll: x, remaining [y, z]
-- weakly consistent iterators --
modified a ConcurrentHashMap while iterating: no exception, size now 6, mappingCount 6, visited >= 3: true
same with a HashMap: ConcurrentModificationException
Common questions
Which blocking queue should I use for a producer–consumer pipeline?
Usually ArrayBlockingQueue or a LinkedBlockingQueue with a capacity. A bound gives backpressure: fast producers wait instead of filling memory. Use PriorityBlockingQueue when the order should follow priority, and DelayQueue when items should become available only after a delay.
How do I stop consumer threads cleanly?
Put a poison pill, a special marker object, into the queue after the last real item. Each consumer that takes it puts it back for the others and exits. Alternatively, interrupt the consumers. take() reacts to interruption by throwing InterruptedException.
Why can't I put null into a BlockingQueue or a ConcurrentHashMap?
These classes use null as a return value that means "nothing there", for example from poll or get. Allowing null elements would make that ambiguous, so they throw NullPointerException.
Is ConcurrentHashMap.size() accurate?
Only when no other thread is modifying the map. While updates are in progress, it returns an estimate. For very large maps, use mappingCount(), which returns a long.
Do concurrent collections throw ConcurrentModificationException?
No. Their iterators are weakly consistent: they work while other threads modify the collection and may or may not show those changes, but they never fail and never return an element twice.
API reference
java.util.concurrent.BlockingQueue<E> and BlockingDeque<E>
| Method | Description |
|---|---|
void put(E e) / E take() | adds / removes, blocking as necessary |
boolean offer(E e, long time, TimeUnit unit) | adds, waiting at most the given time; false on timeout |
E poll(long time, TimeUnit unit) | removes the head, waiting at most the given time; null on timeout |
int drainTo(Collection<? super E> c), int remainingCapacity() | removes all available elements; free space |
putFirst, putLast, takeFirst, takeLast | BlockingDeque: blocking operations at either end |
offerFirst/offerLast(e, time, unit), pollFirst/pollLast(time, unit) | BlockingDeque: timed operations at either end |
Implementations and related types
| Constructor / method | Description |
|---|---|
ArrayBlockingQueue(int capacity), ArrayBlockingQueue(int capacity, boolean fair) | bounded queue backed by a circular array |
LinkedBlockingQueue(), LinkedBlockingQueue(int capacity), LinkedBlockingDeque(...) | linked queue/deque, unbounded or bounded |
PriorityBlockingQueue(), PriorityBlockingQueue(int initialCapacity, Comparator<? super E> c) | unbounded blocking priority heap (default capacity 11) |
DelayQueue<E extends Delayed>() | elements become available after their delay expires |
void transfer(E e), boolean tryTransfer(E e), boolean tryTransfer(E e, long time, TimeUnit unit) | TransferQueue: hand an element directly to a consumer |
ConcurrentLinkedQueue(), ConcurrentSkipListMap(), ConcurrentSkipListSet(Comparator<? super E> c) | non-blocking queue; concurrent sorted map and set |
ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) | defaults 16 and 0.75; the concurrency level is a sizing hint |
long mappingCount() | ConcurrentHashMap: number of mappings as a long |
Summary
- Producer–consumer designs with a
BlockingQueueneed no explicit locking.putandtakeblock when the queue is full or empty, which balances work and provides backpressure. - The method families differ only when the queue is full or empty:
add/remove/elementthrow,offer/poll/peekreturn a failure value (also with timeouts), andput/takeblock.nullelements are forbidden. - Choose
ArrayBlockingQueueorLinkedBlockingQueuefor FIFO,PriorityBlockingQueuefor priority order,DelayQueuefor timed release,TransferQueue/SynchronousQueuefor direct handoff, andLinkedBlockingDequefor both ends. - Stop consumers with a poison pill that each consumer puts back, or with interrupts or executor shutdown.
ConcurrentHashMap,ConcurrentSkipListMap/SetandConcurrentLinkedQueueallow concurrent access with weakly consistent iterators and nonulls. Their structure is safe, but compound actions still need their atomic methods.
Practice Questions
In a producer–consumer program, why prefer put/take over add/remove?
Across threads, the queue can become full or empty at any moment. add and remove would then throw, while put and take simply wait until the operation can succeed. That waiting is exactly the coordination you want.
Why can't a BlockingQueue contain null?
poll and peek return null to mean "no element available", and the timed poll returns null on timeout. If null were a legal element, you couldn't tell a stored null from failure. Inserting null throws NullPointerException.
Several consumer threads read from one queue. How does a single poison pill stop all of them?
Each consumer that takes the pill puts it back into the queue before exiting. The next consumer then finds it and does the same, until every consumer has seen it and stopped.
What does transfer() do that put() doesn't?
put returns as soon as the element is stored in the queue. transfer on a TransferQueue waits until a consumer has actually received the element, so the producer knows the handoff happened.
What does "weakly consistent iterator" mean?
The iterator never throws ConcurrentModificationException and never returns an element twice. It may or may not reflect insertions or removals made after it was created. In other words, it isn't a snapshot: it may show some concurrent changes and miss others, so don't rely on it for an exact view of the collection at any single moment.
Previous: Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Next: Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
Related reading
- Java Primitive Types: Integers and Floating-Point Numbers Explained
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.