Queue and Deque in Java

Learn Java Queue and Deque ordering, including FIFO queues, PriorityQueue ordering, and bounded BlockingQueue backpressure for producers.

published: reading time: 14 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java Queue and Deque ordering, including FIFO queues, PriorityQueue ordering, and bounded BlockingQueue backpressure for producers.

Queue and Deque in Java

Java’s Queue interface is commonly used for FIFO (first-in-first-out) processing, while Deque extends it with operations at both ends. FIFO is common, but each implementation defines its own ordering. PriorityQueue, for example, orders elements by natural order or a comparator rather than insertion order.

Introduction

The Queue interface is often used as a FIFO (first-in-first-out) structure: add at the tail and remove from the head, like a line at a coffee shop. That ordering is common, not guaranteed. Every implementation defines its ordering; PriorityQueue, for instance, puts the smallest element at the head by natural order or by its comparator. Deque adds operations at both ends, so you can use it as a FIFO queue or a LIFO stack depending on which methods you call.

For general queue or deque work, ArrayDeque is a useful starting point. The Java SE API documents amortized constant-time operations and says it is likely faster than LinkedList as a queue, but actual performance depends on the workload and runtime. LinkedList uses linked nodes; do not infer exact memory placement or cache behavior from that structure. PriorityQueue has logarithmic insertion and removal and constant-time head inspection; iterating it is not a sorted traversal, while repeated poll() calls return elements in priority order.

This post compares Queue, Deque, and PriorityQueue; explains the throwing and sentinel-returning method pairs; and shows how to build a max-heap with a reversed comparator. It also covers null restrictions, thread-safe concurrent implementations, and how bounded BlockingQueues slow or reject producers when consumers fall behind.

When to Use Queue

Use Queue when:

  • You need FIFO processing and choose an implementation whose documented ordering is FIFO
  • You are implementing breadth-first search, task scheduling, or producer-consumer patterns
  • You need to buffer elements between a producer and consumer with different processing rates

Do not use Queue when:

  • You need to access elements by index (use List)
  • Order should be based on element priority rather than insertion order
  • You need LIFO (stack) behavior — use a Deque instead

When to Use Deque

Use Deque when:

  • You need to add or remove from both the head and tail
  • You are implementing a double-ended queue, stack, or both simultaneously
  • You need efficient head/tail operations with O(1) performance

PriorityQueue

PriorityQueue is a min-heap by default: its head is the smallest element by natural ordering or a supplied comparator. It does not preserve insertion order, and iterating it does not produce sorted output. The heap property is maintained during insertion and removal; repeatedly calling poll() retrieves elements in priority order.

Mermaid Diagram: Queue Family

graph TD
    A["Queue Interface"] --> B["Deque Interface"]
    B --> C["ArrayDeque"]
    B --> D["LinkedList"]
    A --> E["PriorityQueue"]
    A --> F["BlockingQueue implementations"]
    C --> G["Resizable array<br/>Not synchronized"]
    D --> H["Doubly linked list<br/>Not synchronized"]
    E --> I["Binary heap<br/>O(log n) insert/remove<br/>Not sorted order"]
    F --> J["Thread-safe; may block<br/>e.g., ArrayBlockingQueue"]

Failure Scenarios

Scenario Cause Result
NoSuchElementException Calling remove() / get() on empty queue Runtime crash
NullPointerException Adding null to a queue that does not allow nulls Runtime crash
IllegalStateException Capacity-bounded queue is full Runtime crash or blocking
ClassCastException Elements not mutually comparable in PriorityQueue Runtime crash

Trade-Off Table

Implementation Insert Remove Head Peek Concurrency
ArrayDeque O(1) O(1) O(1) Not synchronized
LinkedList O(1) O(1) O(1) Not synchronized
PriorityQueue O(log n) O(log n) O(1) Not synchronized
ArrayBlockingQueue O(1) O(1) O(1) Thread-safe, bounded, blocking
LinkedBlockingQueue O(1) O(1) O(1) Thread-safe, blocking, optional bound
ConcurrentLinkedQueue O(1) O(1) O(1) Thread-safe, unbounded, non-blocking
ConcurrentLinkedDeque O(1) O(1) O(1) Thread-safe, unbounded, non-blocking
PriorityBlockingQueue O(log n) O(log n) O(1) Thread-safe, unbounded, blocking take

Code Snippets

Queue and BlockingQueue are available since Java 5; ArrayDeque was added in Java 6. The short examples below use Java 5 or later.

ArrayDeque as Stack and Queue

Deque<String> stack = new ArrayDeque<>();
stack.push("first");
stack.push("second");
System.out.println(stack.pop());  // "second"

Deque<String> queue = new ArrayDeque<>();
queue.addLast("task1");
queue.addLast("task2");
System.out.println(queue.removeFirst());  // "task1"

PriorityQueue with Custom Comparator

// Max-heap via reversed comparator
PriorityQueue<int[]> maxHeap = new PriorityQueue<>(
    (a, b) -> Integer.compare(b[1], a[1])  // Compare by second element, descending
);

maxHeap.add(new int[]{1, 5});
maxHeap.add(new int[]{2, 9});
maxHeap.add(new int[]{3, 3});

System.out.println(maxHeap.peek()[1]);  // 9 — highest priority
System.out.println(maxHeap.poll()[1]);   // 9

Draining a Queue

Queue<Integer> buffer = new LinkedList<>();
buffer.add(1);
buffer.add(2);
buffer.add(3);

while (!buffer.isEmpty()) {
    int task = buffer.poll();  // removeFirst() — returns null if empty
    process(task);
}

Backpressure with a Bounded BlockingQueue

A bounded queue limits how many items can wait for a consumer. Choose its capacity based on the memory and queueing delay you can tolerate, then decide what producers should do when it fills. put() waits for space; timed offer() waits up to a deadline and returns false if the queue stays full.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

class BoundedQueueExample {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> tasks = new ArrayBlockingQueue<>(100);
        boolean accepted = tasks.offer(42, 100, TimeUnit.MILLISECONDS);
        System.out.println("accepted = " + accepted);

        if (!accepted) {
            System.out.println("Queue stayed full; reject or retry the task");
        }
    }
}

A bounded queue caps the number of queued items; it does not set a memory budget for objects retained elsewhere in the application. A full queue still needs a policy, such as waiting, retrying, rejecting work, or shedding lower-priority tasks.

Observability Checklist

  • Monitor queue depth to detect producer-consumer imbalances
  • Track poll() vs remove() failures — poll() returning null is often silently ignored
  • Profile PriorityQueue operations for O(n) instead of O(log n) — indicates a broken comparator
  • Log IllegalStateException or block events on bounded queues
  • Monitor for memory pressure from unbounded queue growth

Security Notes

  • ArrayDeque, LinkedList, and PriorityQueue are not synchronized. For shared access, choose a concurrent collection such as ConcurrentLinkedQueue or a blocking implementation such as ArrayBlockingQueue.
  • PriorityQueue is not synchronized; use PriorityBlockingQueue when concurrent priority ordering is needed.
  • A bounded queue limits queued items and can apply backpressure, but it does not cap memory retained outside that queue.
  • When serializing queues, be aware that ArrayDeque serialization only captures elements, not internal state

Common Pitfalls / Anti-Patterns

  1. poll() vs remove(): poll() returns null on empty; remove() throws NoSuchElementException. Using remove() without checking isEmpty() is a bug.
  2. peek() vs element(): Same distinction — peek() returns null on empty; element() throws
  3. PriorityQueue is not sorted: The queue order is heap order, not sorted order. Only peek() always returns the minimum. Iterating a PriorityQueue does NOT yield elements in sorted order.
  4. null elements: PriorityQueue and ArrayDeque do not allow null elements; LinkedList allows null
  5. add() vs offer(): Both insert if capacity allows, but add() throws IllegalStateException on a full bounded queue while offer() returns false

Quick Recap

  • Queue commonly uses FIFO ordering, but each implementation defines its order; Deque supports both ends and PriorityQueue orders by priority
  • ArrayDeque is a useful default Deque; the Java SE API says it is likely faster than LinkedList as a queue, but measure the workload if performance matters
  • PriorityQueue is a min-heap — peek() returns smallest; use a reversed comparator for max-heap
  • poll() / offer() return null/false on failure; remove() / add() throw on failure
  • ArrayDeque, LinkedList, and PriorityQueue are not synchronized. Concurrent options include ConcurrentLinkedQueue, ConcurrentLinkedDeque, and the BlockingQueue implementations.
  • Use a bounded BlockingQueue when producers should wait, time out, or reject work as consumers fall behind; an unbounded queue does not provide that backpressure.

Interview Questions

1. What is the difference between a Queue and a Deque?
`Queue` is commonly used for FIFO processing, but the interface does not require FIFO ordering; each implementation defines its order. `Deque` (double-ended queue) adds operations at **both ends**, so methods such as `addLast()` and `removeFirst()` give FIFO behavior while `push()` and `pop()` give LIFO behavior."

2. How does PriorityQueue maintain order?
`PriorityQueue` orders its head by natural order or its comparator. Its API documents logarithmic insertion and removal and constant-time `peek()`. The iterator is not guaranteed to traverse in priority order; repeatedly call `poll()` when you need ordered retrieval.

3. Why is ArrayDeque preferred over LinkedList for queue/deque operations?
Both provide constant-time end operations in their API contracts, with `ArrayDeque` operations amortized over growth. The Java SE API says `ArrayDeque` is likely faster than `LinkedList` as a queue; benchmark the target workload before treating that as a measured result. Their storage structures differ, but Java does not specify physical placement or cache behavior.

4. What is the time complexity of PriorityQueue's operations?
`offer()` and `poll()` take O(log n), while `peek()` takes O(1) according to the Java SE API. Inserting n items costs O(n log n) in the worst case, the same asymptotic bound as sorting n items. A priority queue is useful when the program needs repeated access to the current head as items arrive.

5. When would you use a BlockingQueue over a regular Queue?
Use a `BlockingQueue` when producer and consumer threads need coordinated waiting. `put()` waits while the queue is full, and `take()` waits while it is empty. Immediate `offer()` and `poll()` return `false` or `null` when they cannot proceed; timed variants wait only up to their limit. With a bounded queue, size the capacity for the memory and delay you can tolerate, then choose what to do if it remains full. `ArrayBlockingQueue` is bounded; `LinkedBlockingQueue` can be given a capacity."

6. What is the difference between `add()`, `offer()`, and `offer(e, timeout, unit)`?
`add()` throws `IllegalStateException` if the queue is full. Immediate `offer()` returns `false`, while `offer(e, timeout, unit)` waits up to the timeout and then returns `false` if no space opens. Use the result to apply the caller's policy, such as retrying or rejecting the work."

7. How does PriorityQueue handle element ordering during `poll()`?
On `poll()`, the root (minimum element) is removed, replaced by the last element, then **sifted down** to restore the heap property — comparing the replacement with its children and swapping if out of order, repeating until the heap property is restored. This is O(log n)."

8. What is a max-heap and how do you create one in Java?
A max-heap stores the largest element at the root (opposite of PriorityQueue's default min-heap). Create one in Java by passing a **reversed comparator** to the PriorityQueue constructor: `new PriorityQueue<>(Comparator.reverseOrder())`. For primitive arrays, use `new PriorityQueue<>(Collections.reverseOrder())`."

9. Why is ArrayDeque preferred over LinkedList for stack operations?
`ArrayDeque` is a useful starting point for stack operations when you do not need `List` methods or `null` elements. Its API documents amortized constant-time operations and says it is likely faster than `LinkedList` as a queue. The exact performance depends on the JVM and workload.

10. What happens when you iterate a PriorityQueue?
The `PriorityQueue` API does not guarantee any particular iteration order. If you need elements in priority order, repeatedly call `poll()` on a copy of the queue or sort an array returned by `toArray()`.

11. Can ArrayDeque grow and shrink?
`ArrayDeque` grows as needed, but the API does not specify its growth factor. It has no `trimToSize()` method; if you need to release excess capacity, create a new deque and copy the elements.

12. What is the difference between `addFirst()` and `push()` in ArrayDeque?
Both `push(e)` and `addFirst(e)` insert at the front and return `void`. The methods have the same behavior in `ArrayDeque`; `push()` is a stack-named alias for `addFirst()`.

13. How does `LinkedBlockingQueue` differ from `LinkedList` in queue implementations?
`LinkedBlockingQueue` is thread-safe and supports blocking `put()` and `take()` operations. Its default capacity is `Integer.MAX_VALUE`, but you can supply a smaller limit. `LinkedList` is not synchronized and has no capacity bound. If you only need thread-safe non-blocking FIFO access, `ConcurrentLinkedQueue` is another option."

14. What is the time complexity of iterating over a PriorityQueue?
The `PriorityQueue` API does not guarantee any particular iteration order. If you need elements in priority order, repeatedly call `poll()` on a copy of the queue or sort an array returned by `toArray()`.

15. When should you use `ArrayDeque` over `LinkedList` for Deque operations?
`ArrayDeque` is a useful default for queue, deque, and stack operations when you do not need `List` methods or `null` elements. Its API documents amortized constant-time operations and says it is likely faster than `LinkedList` as a queue. Measure on your runtime and workload if performance is important.

16. What is the purpose of `Comparator.reverseOrder()` in PriorityQueue?
`new PriorityQueue<>(Comparator.reverseOrder())` creates a **max-heap** (largest element at the front) instead of the default min-heap. The comparator reverses the natural ordering so that `peek()` returns the maximum element rather than the minimum."

17. How does a bounded queue prevent memory exhaustion in producer-consumer patterns?
A bounded queue caps the number of queued elements. With `put()`, producers wait for space; with timed `offer()`, they wait only up to a deadline and can handle a `false` result. Choose a capacity based on item memory and acceptable queueing delay. The bound limits queued items, not all memory the application may retain."

18. What happens when you call `take()` on an empty blocking queue?
`take()` blocks the calling thread indefinitely until an element becomes available. This is different from `poll()` which returns `null` immediately, or `poll(timeout, unit)` which blocks only for the specified duration. Use `take()` when it's acceptable to wait indefinitely for work."

19. What is the difference between `offer(e)` and `add(e)` in bounded queues?
Both insert an element if capacity allows. `add()` throws `IllegalStateException` when the queue is full. `offer()` returns `false` when full. For bounded queues, `offer()` is preferred since it provides a non-exception return value for handling the full state."

20. How does `PriorityQueue` handle elements that are not mutually comparable?
`PriorityQueue` throws `ClassCastException` at insertion time if elements cannot be compared. This occurs when the queue contains elements that don't implement `Comparable` and no `Comparator` was provided at construction, or when the comparator rejects the pair. The exception fires during the sift-up operation after insertion."

Further Reading

Conclusion

For task scheduling and breadth-first traversal, a FIFO queue is often the right fit. The Queue interface does not promise FIFO for every implementation, though; check the ordering contract when choosing one. Deque supports both ends, so it can serve as either a queue or a stack.

ArrayDeque is a common unsynchronized choice for queue, deque, and stack use. PriorityQueue uses a heap ordered by natural order or a comparator, so its head is selected by priority rather than insertion time. For producer-consumer code, a bounded BlockingQueue can slow producers when consumers fall behind, as long as the application has a clear policy for a full queue.

Queue and Deque patterns connect naturally to LinkedList, which also implements Deque and serves as the underlying structure for many queue patterns. For sorted elements with O(log n) operations, TreeSet is worth a look.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals