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

Queue (Java 5) describes a collection with a head: elements are added at one end and taken from the head. Deque (Java 6), short for double-ended queue, allows adding and removing at both the head and the tail, so it can act as a first-in, first-out queue or a last-in, first-out stack.

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 gets an exception, or the reverse.

The two method families
OperationThrows on failureReturns a value
Insert at the tailadd(e)offer(e): false if full
Remove the headremove()poll(): null if empty
Read the headelement()peek(): null if empty
Deque: both endsaddFirst, removeLast, getFirst...offerFirst, pollLast, peekFirst...
Deque as a stackpush(e), pop()peek()
Queue implementations
ClassSinceOrderBest for
ArrayDequeJava 6FIFO or LIFOSingle-threaded queues and stacks
LinkedListJava 1.2 (Deque since 6)FIFO or LIFORarely; allows null
PriorityQueueJava 5Smallest firstPriorities; see PriorityQueue
ArrayBlockingQueue, LinkedBlockingQueueJava 5FIFO, blockingProducer and consumer threads
DelayQueueJava 5By expiry timeTimeouts, scheduled retries
ConcurrentLinkedQueue, ConcurrentLinkedDequeJava 5, Java 7FIFO, lock-freeNon-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.

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

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
  • peek read the head, ann, and poll removed it; element read the new head.
  • On the empty queue, poll and peek returned null, while remove threw NoSuchElementException.
  • Use offer, poll and peek when an empty or full queue is a normal state, and the throwing versions when it means a bug.

A Deque as a stack

ArrayDeque replaces the old Stack class, which is synchronized and extends Vector. The program pushes and pops, uses both ends, and checks bracket balance, the textbook use of a stack.

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

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
  • push adds at the head, so the printed deque shows the most recent element first, and pop removes it.
  • The same object can add and read at either end: getFirst and getLast.
  • The bracket checker pushes each opening bracket and pops when it sees a closing one, failing on a mismatch or on leftovers. (a[b]{c}) balanced, (] and (( did not.
  • The Stack documentation itself recommends Deque. Use 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.

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

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 ArrayBlockingQueue of capacity 2 accepted two offers and refused the third with false. add on the full queue threw IllegalStateException with "Queue full". offer with a timeout waited 50 ms for space before giving up.
  • 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 DelayQueue holds elements until their delay expires. poll returned null immediately because nothing was due yet, and take waited, returning sooner before later.

Producer and consumer threads

A BlockingQueue connects threads: producers put work and consumers take it, each waiting when the queue is full or empty. The queue holds at most two jobs, so the producer has to wait for the consumer.

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

Output
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 put until the consumer had taken one, which is called backpressure: a slow consumer automatically slows the producer down.
  • A special STOP value, a "poison pill", tells the consumer to finish, since take would otherwise wait forever.
  • Thread pools are built on this mechanism; ThreadPoolExecutor takes a BlockingQueue of tasks. More on thread-safe collections is on concurrent collections.

ArrayDeque versus LinkedList

Both implement Deque. The program runs five million offer-and-poll pairs on a queue of about 1,000 elements with each, keeping the fastest of three runs.

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

Output
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)

ArrayDeque was about 1.5 to 2 times as fast across runs. It stores elements in a circular array, so offering and polling just move two indexes, while LinkedList allocates a node for every offer and leaves it for the garbage collector after every poll. ArrayDeque also rejects null, which keeps poll's null result unambiguous. See ArrayList vs LinkedList for the memory side.

Inside ArrayDeque: a circular array

ArrayDeque keeps its elements in one Object[] with two indexes. head points at the first element and tail at the slot after the last. Adding at the tail moves tail forward, polling moves head forward, and both wrap around to index 0 when they pass the end of the array. The program reads those private fields with reflection, which needs --add-opens java.base/java.util=ALL-UNNAMED, to show the queue moving through the array.

Java
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);
    }
}
Output
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 ArrayDeque had an array of length 17. The JDK 21 constructor allocates 16 + 1 slots; one slot always stays empty in this design.
  • After 10 offers and 8 polls, head was 8 and tail 10. Polling did not shift any elements; it cleared slot after slot and moved the index.
  • Twelve more offers filled slots 10 to 16 and then wrapped, leaving tail at 5, below head. The deque still printed in order from 9 to 22, without growing, because 14 elements fit in 17 slots.
  • addFirst(0) moved head 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.
  • While 2,000 elements were added, the array grew from 17 to 36, 74, 111 and on to 2,827. The grow 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.
  • clear() left the array at 2,827 slots. An ArrayDeque never shrinks, so a queue that once held a burst of work keeps that memory until the deque itself is dropped.

When the array is full and the queue has wrapped, grow copies the front part of the elements to the end of the new array so that the order is preserved. Every offer is still O(1) on average, because the copying happens rarely and its cost is spread over many additions.

Traps: Stack order, null and mixed methods

Switching from Stack to ArrayDeque is the right move, but the two do not behave identically, and a Deque has enough methods that it is easy to call one from the wrong family. The program shows five surprises.

Java
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);
    }
}
Output
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 [first, second, third] for Stack and [third, second, first] for ArrayDeque, although peek gave third for both. Stack pushes at the end of its Vector, while the deque pushes at the head. Code that loops over a stack, or tests its toString, changes behaviour after the switch.
  • Stack.get(0) returned first, the bottom element. Because Stack extends Vector, any code can read or change positions under the top, which breaks the idea of a stack.
  • ArrayDeque.offer(null) threw NullPointerException. A LinkedList accepted the null, and then two calls to poll both returned null: the first was the stored element, the second meant the queue was empty, and the caller cannot tell them apart.
  • After offer(1), offer(2) and push(3) the deque was [3, 1, 2], because push adds at the head. Both poll and pop take from the head, so they returned 3 and then 1. Pick one family per deque: offer and poll for a queue, push and pop for a stack.
  • contains and remove(Object) scan from the head. A thousand contains 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 a peek reads a single array slot. If you need to check membership often, keep a HashSet alongside the queue.
  • In Java 21 reversed() returns a live view with the ends swapped, so addFirst("z") on it added at the tail of the original. Before Java 21, descendingIterator() was the usual way to walk a deque backwards.

Which queue to use

Choosing a queue
NeedUse
A FIFO queue in one threadArrayDeque
A stackArrayDeque with push and pop, not Stack
Last n valuesArrayDeque as a sliding window
Smallest or most urgent firstPriorityQueue
Hand work between threads, with backpressureArrayBlockingQueue or bounded LinkedBlockingQueue
Shared queue that never blocksConcurrentLinkedQueue
Elements due at a timeDelayQueue
Empty is normaloffer, poll, peek
Empty is a bugadd, remove, element