Skip to lesson

BlockingQueue: the simpler way

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

BlockingQueueBasicsDemo.javaJava
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());    }}
Output
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, no wait() and no notifyAll() in this program. put blocks while 2 bags are on the shelf, take blocks while it is empty, and the queue does all the locking inside.
  • ArrayBlockingQueue keeps first-in, first-out order, so the bags come out in the order they went in. Both put and take throw InterruptedException, just like wait().

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

QueueMethodsDemo.javaJava
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));    }}
Output
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, add throws IllegalStateException, offer returns false at once, and offer with a timeout waits up to that long for room before returning false. put (not shown here) would wait forever.
  • On an empty queue, remove throws, poll returns null at once, and poll with a timeout waits up to that long for an item. take would wait forever. A BlockingQueue never holds null, so null from poll always means "nothing there".

Example 3 · Tatkal rush: refuse instead of waiting forever

TatkalQueueDemo.javaJava
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();    }}
Output
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 gets null and 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) returns false on full, poll() returns null on empty.
  • Wait up to a time: offer(e, 50, TimeUnit.MILLISECONDS), poll(200, TimeUnit.MILLISECONDS).
  • Wait forever: put(e) and take().

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.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class OfferDemo {
public static void main(String[] args) {
BlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
queue.offer("A");
queue.offer("B");
System.out.println(queue.offer("C"));
System.out.println(queue.poll());
System.out.println(queue.size());
}
}
A 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);.

Java
// 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();   // consumer

The 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

TwoAndTwoQueueDemo.javaJava
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);    }}
Output
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 SharedShelf from the previous lesson, but the whole buffer class is gone: one ArrayBlockingQueue line replaces two guarded methods and every wait/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

QueueExtrasDemo.javaJava
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();    }}
Output
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, and drainTo(list, max) moves several items in one call, both safe with other threads around.
  • A thread blocked in take() or put() wakes up with InterruptedException when 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() and drainTo() work safely with many threads.
  • Use wait/notify to understand the idea, and BlockingQueue to ship code. The Concurrent Collections module compares the other queue types.

Next step

Check your understanding

12 quick questions