BlockingQueue: the simpler way
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A BlockingQueue is a ready-made bounded buffer from java.util.concurrent: put waits while it is full and take waits while it is empty. Everything the last lesson built by hand with wait and notifyAll comes in one tested class.
put() and take() block for you
A BlockingQueue is a thread-safe queue whose put waits when it is full and whose take waits when it is empty.
BlockingQueue<E> is an interface for thread-safe queues whose put(e) blocks (waits) while the queue is full and whose take() blocks while it is empty. ArrayBlockingQueue is the main implementation with a fixed capacity: new ArrayBlockingQueue<>(3).
Example 1 · put and take with ArrayBlockingQueue
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class BlockingQueueBasicsDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> shelf = new ArrayBlockingQueue<>(2); List<String> delivered = new ArrayList<>(); // used only by the rider
Thread warehouse = new Thread(() -> { try { for (int i = 1; i <= 6; i++) { shelf.put("ORD-" + i); // waits while the shelf is full } } catch (InterruptedException e) { return; } }, "warehouse");
Thread rider = new Thread(() -> { try { for (int i = 0; i < 6; i++) { delivered.add(shelf.take()); // waits while the shelf is empty Thread.sleep(20); } } catch (InterruptedException e) { return; } }, "rider");
warehouse.start(); rider.start(); warehouse.join(); rider.join(); System.out.println("Delivered: " + delivered); System.out.println("Left on shelf: " + shelf.size()); }}Delivered: [ORD-1, ORD-2, ORD-3, ORD-4, ORD-5, ORD-6] Left on shelf: 0
What this code does
- There is no
synchronized, nowait()and nonotifyAll()in this program.putblocks while 2 bags are on the shelf,takeblocks while it is empty, and the queue does all the locking inside. ArrayBlockingQueuekeeps first-in, first-out order, so the bags come out in the order they went in. BothputandtakethrowInterruptedException, just likewait().
The queue does the locking, the guards and the waking inside. Producer and consumer code shrinks to one call each, and both calls throw InterruptedException like wait() does.
offer() and poll() with a timeout
Waiting forever is not always right. A booking server should say "busy, retry" rather than hang, and a worker may want to stop when no work comes.
Example 2 · Four ways to add and remove
import java.util.NoSuchElementException;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;
public class QueueMethodsDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> q = new ArrayBlockingQueue<>(2); q.put("A"); q.put("B"); // now full
try { q.add("C"); } catch (IllegalStateException e) { System.out.println("add on full: " + e); } System.out.println("offer on full: " + q.offer("C")); long start = System.nanoTime(); boolean ok = q.offer("C", 100, TimeUnit.MILLISECONDS); long waited = (System.nanoTime() - start) / 1_000_000; System.out.println("offer 100 ms on full: " + ok + " (waited at least 100 ms: " + (waited >= 100) + ")");
q.clear(); // now empty try { q.remove(); } catch (NoSuchElementException e) { System.out.println("remove on empty: " + e); } System.out.println("poll on empty: " + q.poll()); System.out.println("poll 100 ms on empty: " + q.poll(100, TimeUnit.MILLISECONDS)); }}add on full: java.lang.IllegalStateException: Queue full offer on full: false offer 100 ms on full: false (waited at least 100 ms: true) remove on empty: java.util.NoSuchElementException poll on empty: null poll 100 ms on empty: null
What this code does
- On a full queue,
addthrowsIllegalStateException,offerreturnsfalseat once, andofferwith a timeout waits up to that long for room before returningfalse.put(not shown here) would wait forever. - On an empty queue,
removethrows,pollreturnsnullat once, andpollwith a timeout waits up to that long for an item.takewould wait forever. ABlockingQueuenever holdsnull, sonullfrompollalways means "nothing there".
Example 3 · Tatkal rush: refuse instead of waiting forever
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.TimeUnit;
public class TatkalQueueDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> requests = new ArrayBlockingQueue<>(3);
// 10:00 a.m.: five booking requests arrive before the server starts working. for (int i = 1; i <= 5; i++) { String pnr = "PNR-" + (4100 + i); boolean accepted = requests.offer(pnr, 50, TimeUnit.MILLISECONDS); System.out.println(pnr + (accepted ? ": queued" : ": server busy, please retry")); }
Thread worker = new Thread(() -> { try { String pnr; while ((pnr = requests.poll(200, TimeUnit.MILLISECONDS)) != null) { System.out.println("Worker booked " + pnr); } System.out.println("Worker: no request for 200 ms, stopping"); } catch (InterruptedException e) { return; } }, "booking-worker"); worker.start(); worker.join(); }}PNR-4101: queued PNR-4102: queued PNR-4103: queued PNR-4104: server busy, please retry PNR-4105: server busy, please retry Worker booked PNR-4101 Worker booked PNR-4102 Worker booked PNR-4103 Worker: no request for 200 ms, stopping
What this code does
- The queue holds 3 requests. The 4th and 5th wait up to 50 ms for room, get none and are refused, so the caller can show "please retry" instead of hanging.
- The worker uses
poll(200, MILLISECONDS): it waits for work, but if nothing arrives for 200 ms it getsnulland stops. Timed methods turn "wait forever" into "wait this long, then decide".
offer(e, time, unit) waits up to the given time for room and returns false if none came; poll(time, unit) waits up to that time for an item and returns null if none came.
- Throw an exception:
add(e)on full (IllegalStateException),remove()on empty (NoSuchElementException). - Return at once:
offer(e)returnsfalseon full,poll()returnsnullon empty. - Wait up to a time:
offer(e, 50, TimeUnit.MILLISECONDS),poll(200, TimeUnit.MILLISECONDS). - Wait forever:
put(e)andtake().
Predict the output
Predict the output
These calls never block, so the output is the same on every run.
Round 1 of 2
A queue with room for 2 orders gets 3 offers.
BlockingQueue refuses null elements (NullPointerException), so a null from poll always means "nothing there".Rewriting the bounded buffer with ArrayBlockingQueue
The hand-written buffer had a class with two guarded methods, wait() in while loops and notifyAll() on both sides. With ArrayBlockingQueue all of it becomes one field: BlockingQueue<String> shelf = new ArrayBlockingQueue<>(3);.
// before: class BoundedBuffer with synchronized put/take,// while (...) wait(); and notifyAll() on both sides
// after:BlockingQueue<String> shelf = new ArrayBlockingQueue<>(3);shelf.put("ORD-1"); // producerString bag = shelf.take(); // consumerThe producer calls shelf.put(item) and the consumer calls shelf.take(). Several producers and consumers can share the queue with no extra code.
Example 4 · The two-warehouse, two-rider buffer, rewritten
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class TwoAndTwoQueueDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> shelf = new ArrayBlockingQueue<>(3); List<List<String>> perRider = new ArrayList<>(); List<Thread> threads = new ArrayList<>();
for (String warehouse : new String[] {"D", "B"}) { threads.add(new Thread(() -> { try { for (int i = 1; i <= 5; i++) { shelf.put(warehouse + "-" + i); } } catch (InterruptedException e) { return; } }, "warehouse-" + warehouse)); } for (int r = 1; r <= 2; r++) { List<String> mine = new ArrayList<>(); perRider.add(mine); threads.add(new Thread(() -> { try { for (int i = 0; i < 5; i++) { mine.add(shelf.take()); } } catch (InterruptedException e) { return; } }, "rider-" + r)); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); }
List<String> all = new ArrayList<>(); boolean inWarehouseOrder = true; for (List<String> mine : perRider) { all.addAll(mine); int lastD = 0; int lastB = 0; for (String bag : mine) { int n = Integer.parseInt(bag.substring(2)); if (bag.startsWith("D")) { inWarehouseOrder &= n > lastD; lastD = n; } else { inWarehouseOrder &= n > lastB; lastB = n; } } } Collections.sort(all); System.out.println("Taken: " + all); System.out.println("Each rider got each warehouse's bags in order: " + inWarehouseOrder); }}Taken: [B-1, B-2, B-3, B-4, B-5, D-1, D-2, D-3, D-4, D-5] Each rider got each warehouse's bags in order: true
What this code does
- This is the same job as the hand-written
SharedShelffrom the previous lesson, but the whole buffer class is gone: oneArrayBlockingQueueline replaces two guarded methods and everywait/notifyAll. - Which rider gets which bag changes on every run, so the program prints only what is always true. Each rider list is filled by one thread and read by main only after
join().
Why ready-made tools beat hand-written wait/notify
Hand-written wait/notify code fails in quiet ways: an if instead of while, a notify() that wakes the wrong thread, a missing notify. The bug shows up only under load. The java.util.concurrent classes are written and tested by JDK experts and used in millions of programs.
Example 5 · Extras you get for free
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;
public class QueueExtrasDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> q = new ArrayBlockingQueue<>(5); q.put("A"); q.put("B"); q.put("C"); System.out.println("size " + q.size() + ", room left " + q.remainingCapacity());
List<String> batch = new ArrayList<>(); int moved = q.drainTo(batch, 2); // take up to 2 at once System.out.println("drainTo moved " + moved + ": " + batch + ", queue now " + q);
Thread rider = new Thread(() -> { try { while (true) { System.out.println("Rider took " + q.take()); } } catch (InterruptedException e) { System.out.println("Rider: interrupted while waiting in take(), stopping"); } }, "rider"); rider.start();
while (rider.getState() != Thread.State.WAITING) { // demo only: let it reach take() Thread.sleep(5); } rider.interrupt(); rider.join(); }}size 3, room left 2 drainTo moved 2: [A, B], queue now [C] Rider took C Rider: interrupted while waiting in take(), stopping
What this code does
remainingCapacity()tells how much room is left, anddrainTo(list, max)moves several items in one call, both safe with other threads around.- A thread blocked in
take()orput()wakes up withInterruptedExceptionwhen it is interrupted, so a blocked worker can always be stopped. The next lesson builds clean shutdown on this.
- No guard or notify mistakes to make: the queue handles them inside.
- Timeouts (
offer,poll) and interrupt support are built in. - Extras such as
remainingCapacity()anddrainTo()work safely with many threads. - Use
wait/notifyto understand the idea, andBlockingQueueto ship code. The Concurrent Collections module compares the other queue types.
Next step
Check your understanding
12 quick questions