Queue and Deque
A Queue hands elements out in a defined order, usually first in, first out, and a Deque can add and remove at both ends, which also makes it a stack. Java has one interface pair and many implementations, from ArrayDeque to blocking queues for threads. This page explains the two method families, uses a deque as a stack and a sliding window, covers bounded, blocking and delay queues, and measures ArrayDeque against LinkedList.
Contents
The Queue and Deque interfaces
QueueDeque
Every operation exists in two forms. One throws an exception when it cannot proceed; the other returns a special value. Mixing them up is the most common queue bug, because code that expects null
| Operation | Throws on failure | Returns a value |
|---|---|---|
| Insert at the tail | add(e) | offer(e)false |
| Remove the head | remove() | poll()null |
| Read the head | element() | peek()null |
| Deque: both ends | addFirstremoveLastgetFirst | offerFirstpollLastpeekFirst |
| Deque as a stack | push(e)pop() | peek() |
| Class | Since | Order | Best for |
|---|---|---|---|
ArrayDeque | Java 6 | FIFO or LIFO | Single-threaded queues and stacks |
LinkedList | Java 1.2 (Deque since 6) | FIFO or LIFO | Rarely; allows null |
PriorityQueue | Java 5 | Smallest first | Priorities; see |
ArrayBlockingQueueLinkedBlockingQueue | Java 5 | FIFO, blocking | Producer and consumer threads |
DelayQueue | Java 5 | By expiry time | Timeouts, scheduled retries |
ConcurrentLinkedQueueConcurrentLinkedDeque | Java 5, Java 7 | FIFO, lock-free | Non-blocking shared queues |
The examples were run on JDK 21.
Queue methods and their failure behaviour
A queue of three names is drained, and then each read and remove method is called on the empty queue to show which ones throw.
import java.util.ArrayDeque;
import java.util.NoSuchElementException;
import java.util.Queue;
public class QueueMethods {
public static void main(String[] args) {
Queue<String> line = new ArrayDeque<>(); // first in, first out
line.offer("ann");
line.offer("bob");
line.add("cy");
System.out.println("queue: " + line);
System.out.println("peek: " + line.peek());
System.out.println("poll: " + line.poll() + ", left " + line);
System.out.println("element: " + line.element());
line.clear();
// The two families differ only on an empty (or full) queue
System.out.println("poll on empty: " + line.poll());
System.out.println("peek on empty: " + line.peek());
try {
line.remove();
} catch (NoSuchElementException e) {
System.out.println("remove on empty: NoSuchElementException");
}
}
}
Output:
queue: [ann, bob, cy]
peek: ann
poll: ann, left [bob, cy]
element: bob
poll on empty: null
peek on empty: null
remove on empty: NoSuchElementException
read the head,peek , andann removed it;poll read the new head.element- On the empty queue,
andpoll returnedpeek , whilenull threwremove .NoSuchElementException - Use
,offer andpoll when an empty or full queue is a normal state, and the throwing versions when it means a bug.peek
A Deque as a stack
ArrayDequeStackVector
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
public class DequeAsStack {
// Check balanced brackets with a stack
static boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
String open = "([{";
String close = ")]}";
for (char c : s.toCharArray()) {
if (open.indexOf(c) >= 0) {
stack.push(c);
} else if (close.indexOf(c) >= 0) {
char expected = open.charAt(close.indexOf(c));
if (stack.isEmpty() || stack.pop() != expected) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Deque<Integer> stack = new ArrayDeque<>(); // last in, first out
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("stack: " + stack + " (head on the left)");
System.out.println("pop: " + stack.pop() + ", left " + stack);
// Both ends at once
Deque<String> d = new ArrayDeque<>();
d.offerFirst("b");
d.offerFirst("a");
d.offerLast("c");
System.out.println("deque: " + d + " first=" + d.peekFirst() + " last=" + d.peekLast());
for (String s : List.of("(a[b]{c})", "(]", "((", "x")) {
System.out.println(s + " balanced? " + balanced(s));
}
}
}
Output:
stack: [3, 2, 1] (head on the left)
pop: 3, left [2, 1]
deque: [a, b, c] first=a last=c
(a[b]{c}) balanced? true
(] balanced? false
(( balanced? false
x balanced? true
adds at the head, so the printed deque shows the most recent element first, andpush removes it.pop- The same object can add and read at either end:
andgetFirst .getLast - The bracket checker pushes each opening bracket and pops when it sees a closing one, failing on a mismatch or on leftovers.
balanced,(a[b]{c}) and(] did not.(( - The
documentation itself recommendsStack . UseDeque .Deque<T> stack = new ArrayDeque<>()
Bounded queues, sliding windows and delays
Three specialized uses: a queue with a capacity limit, a deque that keeps the last few values, and a queue whose elements only become available after a delay.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class BoundedAndSpecial {
record Reminder(String text, long dueNanos) implements Delayed {
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(dueNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed o) {
return Long.compare(getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS));
}
}
public static void main(String[] args) throws InterruptedException {
// A bounded queue: offer returns false when full, add throws
BlockingQueue<String> bounded = new ArrayBlockingQueue<>(2);
System.out.println("offer a: " + bounded.offer("a") + ", offer b: " + bounded.offer("b")
+ ", offer c: " + bounded.offer("c"));
try {
bounded.add("c");
} catch (IllegalStateException e) {
System.out.println("add on a full queue: IllegalStateException: " + e.getMessage());
}
System.out.println("offer with timeout: "
+ bounded.offer("c", 50, TimeUnit.MILLISECONDS) + " after waiting 50 ms");
System.out.println("remainingCapacity: " + bounded.remainingCapacity());
// A sliding window of the last 3 values with ArrayDeque
Deque<Integer> window = new ArrayDeque<>();
for (int x : new int[] {5, 8, 2, 9, 4}) {
window.addLast(x);
if (window.size() > 3) {
window.removeFirst();
}
System.out.println("window after " + x + ": " + window);
}
// DelayQueue: elements become available only when their delay expires
DelayQueue<Reminder> reminders = new DelayQueue<>();
long now = System.nanoTime();
reminders.add(new Reminder("later", now + TimeUnit.MILLISECONDS.toNanos(80)));
reminders.add(new Reminder("sooner", now + TimeUnit.MILLISECONDS.toNanos(20)));
System.out.println("poll immediately: " + reminders.poll());
System.out.println("take: "
+ reminders.take().text() + ", then " + reminders.take().text());
}
}
Output:
offer a: true, offer b: true, offer c: false
add on a full queue: IllegalStateException: Queue full
offer with timeout: false after waiting 50 ms
remainingCapacity: 0
window after 5: [5]
window after 8: [5, 8]
window after 2: [5, 8, 2]
window after 9: [8, 2, 9]
window after 4: [2, 9, 4]
poll immediately: null
take: sooner, then later
- An
of capacity 2 accepted two offers and refused the third withArrayBlockingQueue .false on the full queue threwadd with "Queue full".IllegalStateException with a timeout waited 50 ms for space before giving up.offer - A sliding window adds at the tail and removes from the head once it exceeds its size, keeping the last three values: useful for moving averages and rate limits.
- A
holds elements until their delay expires.DelayQueue returnedpoll immediately because nothing was due yet, andnull waited, returningtake beforesooner .later
Producer and consumer threads
A BlockingQueueputtake
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingHandOff {
public static void main(String[] args) throws InterruptedException {
// Capacity 2: the producer must wait whenever the consumer falls behind
BlockingQueue<String> jobs = new ArrayBlockingQueue<>(2);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 4; i++) {
jobs.put("job-" + i); // blocks while the queue is full
System.out.println("produced job-" + i);
}
jobs.put("STOP");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
while (true) {
String job = jobs.take(); // blocks while the queue is empty
if (job.equals("STOP")) {
break;
}
Thread.sleep(50); // slow worker
System.out.println(" consumed " + job);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
System.out.println("done, offer on a full queue would return false instead of waiting");
}
}
Output (the interleaving of the two threads can differ between runs):
produced job-1
produced job-2
produced job-3
consumed job-1
produced job-4
consumed job-2
consumed job-3
consumed job-4
done, offer on a full queue would return false instead of waiting
- The producer added two jobs and then blocked in
until the consumer had taken one, which is called backpressure: a slow consumer automatically slows the producer down.put - A special
value, a "poison pill", tells the consumer to finish, sinceSTOP would otherwise wait forever.take - Thread pools are built on this mechanism;
takes aThreadPoolExecutor of tasks. More on thread-safe collections is onBlockingQueueconcurrent collections .
ArrayDeque versus LinkedList
Both implement Deque
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.function.Supplier;
public class DequeSpeed {
public static void main(String[] args) {
int n = 5000000;
System.out.printf("%,d offer + poll pairs on a queue of about 1,000 elements%n", n);
time("ArrayDeque", ArrayDeque::new, n);
time("LinkedList", LinkedList::new, n);
}
static void time(String name, Supplier<Deque<Integer>> factory, int n) {
long best = Long.MAX_VALUE;
long sum = 0;
for (int run = 0; run < 3; run++) {
Deque<Integer> q = factory.get();
for (int i = 0; i < 1000; i++) {
q.offer(i);
}
sum = 0;
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
q.offer(i & 1023);
sum += q.poll();
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-11s %6.1f ms (checksum %d)%n", name, best / 1e6, sum);
}
}
Output (rough timings, 2-CPU Linux, JDK 21):
5,000,000 offer + poll pairs on a queue of about 1,000 elements
ArrayDeque 40.4 ms (checksum 2557416096)
LinkedList 72.9 ms (checksum 2557416096)
ArrayDequeLinkedListofferpollArrayDequenullpollnull
Inside ArrayDeque: a circular array
ArrayDequeObject[]headtailtailhead--add-opens java.base/java.util=ALL-UNNAMED
import java.lang.reflect.Field;
import java.util.ArrayDeque;
public class DequeInternals {
static Field elements;
static Field head;
static Field tail;
public static void main(String[] args) throws ReflectiveOperationException {
elements = ArrayDeque.class.getDeclaredField("elements");
head = ArrayDeque.class.getDeclaredField("head");
tail = ArrayDeque.class.getDeclaredField("tail");
elements.setAccessible(true);
head.setAccessible(true);
tail.setAccessible(true);
ArrayDeque<Integer> q = new ArrayDeque<>();
show("new ArrayDeque()", q);
for (int i = 1; i <= 10; i++) {
q.offer(i);
}
show("after 10 offers", q);
for (int i = 0; i < 8; i++) {
q.poll();
}
show("after 8 polls", q);
for (int i = 11; i <= 22; i++) {
q.offer(i);
}
show("after 12 more offers (tail wrapped)", q);
q.addFirst(0);
show("addFirst(0)", q);
// Growth: below 64 slots the array roughly doubles, above it grows by half
ArrayDeque<Integer> big = new ArrayDeque<>();
int last = -1;
StringBuilder sizes = new StringBuilder();
for (int i = 0; i < 2000; i++) {
big.add(i);
int cap = ((Object[]) elements.get(big)).length;
if (cap != last) {
sizes.append(cap).append(' ');
last = cap;
}
}
System.out.println("array lengths while adding 2,000: " + sizes.toString().trim());
big.clear();
System.out.println("after clear(): size " + big.size() + ", array length "
+ ((Object[]) elements.get(big)).length);
}
static void show(String label, ArrayDeque<Integer> q) throws IllegalAccessException {
Object[] es = (Object[]) elements.get(q);
System.out.printf("%-36s length %2d, head %2d, tail %2d, %s%n", label, es.length,
head.getInt(q), tail.getInt(q), q);
}
}
new ArrayDeque() length 17, head 0, tail 0, []
after 10 offers length 17, head 0, tail 10, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
after 8 polls length 17, head 8, tail 10, [9, 10]
after 12 more offers (tail wrapped) length 17, head 8, tail 5, [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
addFirst(0) length 17, head 7, tail 5, [0, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
array lengths while adding 2,000: 17 36 74 111 166 249 373 559 838 1257 1885 2827
after clear(): size 0, array length 2827
- A new
had an array of length 17. The JDK 21 constructor allocatesArrayDeque slots; one slot always stays empty in this design.16 + 1 - After 10 offers and 8 polls,
was 8 andhead 10. Polling did not shift any elements; it cleared slot after slot and moved the index.tail - Twelve more offers filled slots 10 to 16 and then wrapped, leaving
at 5, belowtail . The deque still printed in order from 9 to 22, without growing, because 14 elements fit in 17 slots.head movedaddFirst(0) back from 8 to 7. Adding at the front costs the same as adding at the back, which is why one class can serve as both queue and stack.head- While 2,000 elements were added, the array grew from 17 to 36, 74, 111 and on to 2,827. The
method in the JDK 21 source adds the old length plus 2 while the array is under 64 slots, and half the old length after that.grow left the array at 2,827 slots. Anclear() never shrinks, so a queue that once held a burst of work keeps that memory until the deque itself is dropped.ArrayDeque
When the array is full and the queue has wrapped, growoffer
Traps: Stack order, null and mixed methods
Switching from StackArrayDequeDeque
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class DequeTraps {
public static void main(String[] args) {
// 1. Stack and ArrayDeque iterate in opposite orders
Stack<String> oldStack = new Stack<>();
Deque<String> newStack = new ArrayDeque<>();
for (String s : List.of("first", "second", "third")) {
oldStack.push(s);
newStack.push(s);
}
System.out.println("Stack printed: " + oldStack + ", peek " + oldStack.peek());
System.out.println("ArrayDeque printed: " + newStack + ", peek " + newStack.peek());
System.out.println("Stack.get(0): " + oldStack.get(0)
+ " (a Vector method that reaches under the top)");
// 2. null: ArrayDeque refuses it, LinkedList makes poll ambiguous
Deque<String> array = new ArrayDeque<>();
try {
array.offer(null);
} catch (NullPointerException e) {
System.out.println("ArrayDeque.offer(null): NullPointerException");
}
Queue<String> linked = new LinkedList<>();
linked.offer(null);
System.out.println("LinkedList with one null: poll() = " + linked.poll()
+ ", then poll() = " + linked.poll() + " (same answer, different meaning)");
// 3. Calling a stack method on a queue, or the reverse, flips the order
Deque<Integer> d = new ArrayDeque<>();
d.offer(1);
d.offer(2);
d.push(3);
System.out.println("offer 1, offer 2, push 3: " + d + ", poll() " + d.poll()
+ ", pop() " + d.pop());
// 4. remove(Object) and contains walk the whole deque
Deque<Integer> many = new ArrayDeque<>();
for (int i = 0; i < 200000; i++) {
many.add(i);
}
long scan = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
for (int i = 0; i < 1000; i++) {
many.contains(-1);
}
scan = Math.min(scan, System.nanoTime() - t0);
}
System.out.printf("1,000 contains calls on 200,000 elements: %.0f ms, best of 3%n",
scan / 1e6);
// 5. Java 21: reversed() is a view, descendingIterator has been there since Java 6
Deque<String> tasks = new ArrayDeque<>(List.of("a", "b", "c"));
Deque<String> back = tasks.reversed();
back.addFirst("z");
System.out.println("reversed().addFirst(z) added at the tail: " + tasks);
}
}
Stack printed: [first, second, third], peek third
ArrayDeque printed: [third, second, first], peek third
Stack.get(0): first (a Vector method that reaches under the top)
ArrayDeque.offer(null): NullPointerException
LinkedList with one null: poll() = null, then poll() = null (same answer, different meaning)
offer 1, offer 2, push 3: [3, 1, 2], poll() 3, pop() 1
1,000 contains calls on 200,000 elements: 223 ms, best of 3
reversed().addFirst(z) added at the tail: [a, b, c, z]
- The same three pushes printed as
for[first, second, third] andStack for[third, second, first] , althoughArrayDeque gavepeek for both.third pushes at the end of itsStack , while the deque pushes at the head. Code that loops over a stack, or tests itsVector , changes behaviour after the switch.toString returnedStack.get(0) , the bottom element. Becausefirst extendsStack , any code can read or change positions under the top, which breaks the idea of a stack.Vector threwArrayDeque.offer(null) . ANullPointerException accepted theLinkedList , and then two calls tonull both returnedpoll : the first was the stored element, the second meant the queue was empty, and the caller cannot tell them apart.null- After
,offer(1) andoffer(2) the deque waspush(3) , because[3, 1, 2] adds at the head. Bothpush andpoll take from the head, so they returned 3 and then 1. Pick one family per deque:pop andoffer for a queue,poll andpush for a stack.pop andcontains scan from the head. A thousandremove(Object) calls on 200,000 elements took a couple of hundred milliseconds in the best of three runs on this 2-CPU machine, roughly 0.2 ms per scan, while acontains reads a single array slot. If you need to check membership often, keep apeek alongside the queue.HashSet- In Java 21
returns a live view with the ends swapped, soreversed() on it added at the tail of the original. Before Java 21,addFirst("z") was the usual way to walk a deque backwards.descendingIterator()
Which queue to use
| Need | Use |
|---|---|
| A FIFO queue in one thread | ArrayDeque |
| A stack | ArrayDequepushpopStack |
| Last n values | ArrayDeque |
| Smallest or most urgent first | PriorityQueue |
| Hand work between threads, with backpressure | ArrayBlockingQueueLinkedBlockingQueue |
| Shared queue that never blocks | ConcurrentLinkedQueue |
| Elements due at a time | DelayQueue |
| Empty is normal | offerpollpeek |
| Empty is a bug | addremoveelement |