BlockingQueue

How Java's BlockingQueue interface passes items safely between threads, and how its implementations differ: size limits, ordering, delays and direct hand-over.

Share

Contents

Introduction

BlockingQueue is an interface in the java.util.concurrent package, added in Java 5, for passing items from one thread to another. One thread, the producer, puts items in, and another thread, the consumer, takes them out. This producer-consumer pattern is one of the most common ways to split work between threads: one thread receives work, and one or more threads process it.

BlockingQueue extends the ordinary Queue interface and adds two methods that wait. put(item) waits while the queue is full, and take() waits while it is empty. A waiting thread sleeps and uses no CPU until it can continue. The queue does all the locking inside, so the producer and consumer code needs none.

Because BlockingQueue is an interface, you always create one of its implementations. The JDK has several. They differ in whether they limit how many items they hold, in what order the items come out, and whether they hold items at all. This page introduces them one at a time.

A producer thread puts items into a queue with room for 3; a consumer thread takes the oldest item out. The queue is full, so item 4 waits at put().

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() waits until the consumer takes an item out. On the other side, if the queue were empty, the consumer's take() would wait until a new item arrived.

The examples on this page were run with Java 25.

put() and take()

put(item) adds an item at the end of the queue, waiting first if the queue is full. take() removes the item at the front, waiting first if the queue is empty. Together they let a fast thread and a slow thread work at their own speeds, with the queue absorbing the difference.

The simplest implementation to start with is ArrayBlockingQueue, which stores its items in an array of a fixed size, so it can never hold more items than that size. Consider the following example, where a producer puts six items into an ArrayBlockingQueue with room for three, and a consumer takes one item every 200 ms:

Java
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:

Java
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:

Output
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() made the producer wait until the consumer took item 1 out. Items 5 and 6 went in 200 ms apart for the same reason.

The last line shows that the items were taken in the order they were put in. An ArrayBlockingQueue hands out the oldest item first. This is called FIFO, short for first in, first out.

Notice what the program does not contain: no lock, no synchronized block, no wait() or notify(). The two threads share the queue safely because the queue does the locking itself.

Bounded and unbounded queues

A bounded queue has a maximum size, like the ArrayBlockingQueue above. When it is full, put() waits, so the producer can never get more than that many items ahead of the consumer. An unbounded queue has no such limit: adding never waits, and the queue keeps growing for as long as the producer is faster than the consumer. Which of the two you choose decides what happens when the consumer falls behind.

LinkedBlockingQueue is the usual unbounded choice. It stores its items in a linked list, a chain of small objects with one per item, and if you create it without a size, it has no practical limit. You can also give it a size, which makes it bounded.

The example below adds items with offer() instead of put(). offer(item) adds the item and returns true if there is room; if the queue is full, it returns false straight away instead of waiting. Consider the following example, where a producer offers two million items while no consumer is taking any, first to an unbounded LinkedBlockingQueue and then to an ArrayBlockingQueue with room for 10,000:

Java
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
Java
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:

Output
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 Integer on a 64-bit JVM. Real items are usually larger, often hundreds of bytes, so if the consumer stays behind for long, the program eventually runs out of memory with an OutOfMemoryError.

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 LinkedBlockingQueue created without a size has a limit of Integer.MAX_VALUE, about 2.1 billion items, far more than memory can hold. The same queue is inside Executors.newFixedThreadPool, so a thread pool created that way has no useful limit on waiting tasks either. In most programs, give the queue a size.

Stopping a consumer

A consumer usually runs in a loop that calls take(). When the producer has finished, the queue becomes empty and take() waits forever, so the consumer needs a way to learn that it should stop. There are two common ways.

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:

Java
static final Task STOP = new Task(-1);   // the poison pill

Task task = queue.take();
if (task == STOP) {
    return;                              // stop consuming
}
Java
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:

Output
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 ==, which compares the object itself rather than its contents, so a real task can never be mistaken for the pill.

Interrupt

The other way is to call interrupt() on the consumer thread. take() and put() respond to an interrupt by throwing InterruptedException, which ends the loop. Consider the following example, which interrupts a consumer that is waiting on an empty queue, and then calls take() on a queue that still holds items, from a thread that has already been interrupted:

Java
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:

Output
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 InterruptedException and stopped. Now look at the second line: once a thread has been interrupted, its next take() throws at once, even though three items were still waiting.

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 block.

Taking items in batches with drainTo

drainTo(collection, max) moves up to max waiting items from the queue into a collection in one call, without waiting for more. It is the tool for handling items in batches, for example when writing to a database or a file is cheaper for ten rows at once than for one. The usual pattern is to wait for the first item with take(), then drain whatever else is already there:

Java
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() once it has nothing left to do:

Java
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:

Output
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() waited for one item, and drainTo() added whatever else was waiting, up to 9 more. When items arrive slowly, a batch goes out with a single item instead of waiting to fill up; when they arrive quickly, every batch is full. The last line shows the consumer stopping on the interrupt with nothing left in the queue.

drainTo() is also faster than calling poll() in a loop, because it takes the queue's lock once for the whole batch.

PriorityBlockingQueue: most urgent item first

The queues so far hand out the oldest item first. A PriorityBlockingQueue hands out the item that comes first by a comparison you give it instead, so urgent items can overtake older ones. You pass the comparison as a Comparator when you create the queue:

Java
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:

Java
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:

Output
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 PriorityBlockingQueue is unbounded, so put() never waits, and the protection described in Bounded and unbounded queues does not apply.

DelayQueue: items that become ready later

A DelayQueue holds items that each become ready at a certain time, and its take() hands out an item only once that time has come. It suits work that must happen later, such as retrying a failed operation after a pause, or expiring entries after a timeout.

An item in a DelayQueue must implement the Delayed interface. Its getDelay() method says how long until the item is ready, and its compareTo() method puts the item that is ready soonest first. Consider the following example, where task 1 becomes ready after 300 ms and task 2 after 100 ms:

Java
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:

Output
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() right away returned null, even though the queue holds two tasks, because neither was ready yet. Then take() waited and returned task 2 after about 100 ms and task 1 after about 300 ms: in the order they became ready, not the order they were put in.

A DelayQueue is unbounded too. If the items are tasks to run later, a ScheduledExecutorService is usually simpler, because it also runs them for you.

SynchronousQueue and LinkedTransferQueue: direct hand-over

The queues so far store items until a consumer is ready. A SynchronousQueue stores nothing at all: put() waits until another thread calls take(), and the item passes directly from one thread to the other. A LinkedTransferQueue is an unbounded queue that stores items normally, but can also hand an item directly to a waiting consumer when you ask it to, with transfer() or tryTransfer().

Consider the following example, where the consumer only arrives after 200 ms:

Java
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:

Output
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) returned false, because no consumer was waiting to take the item, and a SynchronousQueue has nowhere to keep it. The second line shows put(2) waiting about 200 ms, until the consumer arrived and took item 2.

Executors.newCachedThreadPool() is built on this. A new task is handed straight to an idle thread if one is waiting; if none is, the pool starts a new thread. The ThreadPoolExecutor page shows this in detail.

The last two lines are the LinkedTransferQueue. put(3) stored item 3 like any queue. tryTransfer(4) hands item 4 over only if a consumer is already waiting; none was, so it returned false and did not store the item. The queue still holds only item 3.

Because every item needs both threads to meet, a SynchronousQueue is much slower than a normal queue for moving many items. Use it when the producer should wait for a consumer, not for bulk transfer.

The four ways to call each operation

put() and take() wait, and offer() gives up at once. These belong to a fuller set: for adding, removing and looking at an item, there is a method that throws an exception, one that returns a special value, one that waits, and one that waits only for a time you give it. Consider an ArrayBlockingQueue with room for one item, first full and then empty:

Java
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:

Output
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() threw an exception, offer() returned false at once, and the timed offer() waited 200 ms before returning false. On the empty queue, poll() returned null instead of waiting. The last line shows that no blocking queue accepts null, because poll() uses null to mean "nothing there".

The table lists the whole set:

BlockingQueue methods by what they do when the queue is full or empty
OperationThrowsReturns a special valueWaitsWaits up to a time
Addadd(e)offer(e): falseput(e)offer(e, time, unit): false
Removeremove()poll(): nulltake()poll(time, unit): null
Look at the next itemelement()peek(): nullNoneNone

add(), remove() and element() exist because a BlockingQueue is also a Collection. Between threads, a full or empty queue is normal rather than an error, so prefer put() and take(), or offer() and poll(). The timed versions keep a thread responsive: a consumer that waits at most a second at a time can check in between whether it should stop.

How it works inside

An ArrayBlockingQueue is an array used in a circle, guarded by one lock, a ReentrantLock, with two conditions on it named notEmpty and notFull. A condition is a place where threads wait until another thread signals that something has changed. take() takes the lock, waits on notEmpty while the queue is empty, removes the item, and signals notFull so that a waiting put() can continue. put() does the reverse. A LinkedBlockingQueue uses two locks, one for each end of its list, so a producer and a consumer rarely wait for each other. The locks and conditions page builds the same structure by hand.

The queue also makes the item itself safe to read. The BlockingQueue documentation guarantees that everything a thread did before putting an item into the queue is visible to the thread that takes it out; in the terms of the Java Memory Model, the put happens-before the take. So the producer can fill in an ordinary object, with no volatile fields or locks, and the consumer is guaranteed to see every field as it was written. The Java Memory Model page explains why that is not automatic between threads.

Recap

One implementation did not appear above: LinkedBlockingDeque, which can add and remove items at both ends, for example to put an item back at the front. The table compares all of them:

The BlockingQueue implementations in the JDK
ClassSinceLimitOrderGood for
ArrayBlockingQueueJava 5Fixed, set when createdOldest firstProducer-consumer with predictable memory
LinkedBlockingQueueJava 5Optional; without one, Integer.MAX_VALUEOldest firstProducer-consumer where both sides run hard
LinkedBlockingDequeJava 6OptionalEither endPutting items back at the front
PriorityBlockingQueueJava 5NoneBy your comparisonUrgent items first
DelayQueueJava 5NoneBy ready timeRetries, timeouts, delayed work
SynchronousQueueJava 5Holds nothingDirect hand-overMaking the producer wait for a consumer
LinkedTransferQueueJava 7NoneOldest firstQueueing that can also hand over directly
Which queue or method to use
SituationUse
Passing items between threadsArrayBlockingQueue or LinkedBlockingQueue, with a size limit
Some items are more urgentPriorityBlockingQueue, plus a sequence number if equal items must keep their order
Items become ready at a set timeDelayQueue, or a ScheduledExecutorService if the items are tasks
Each item goes straight to a waiting consumerSynchronousQueue
Handling items in batchesWait with take(), then drainTo()
Stopping consumers after all items are handledOne poison pill per consumer
Stopping consumers quicklyinterrupt()

If the work is tasks rather than data, an ExecutorService manages the queue and the threads for you. For queues used without waiting, see queues and deques; for threads that wait for each other without passing items, see CountDownLatch and CyclicBarrier.