Queue and Deque in Java
Learn Java Queue and Deque ordering, including FIFO queues, PriorityQueue ordering, and bounded BlockingQueue backpressure for producers.
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()vsremove()failures —poll()returningnullis often silently ignored - Profile
PriorityQueueoperations for O(n) instead of O(log n) — indicates a broken comparator - Log
IllegalStateExceptionor block events on bounded queues - Monitor for memory pressure from unbounded queue growth
Security Notes
ArrayDeque,LinkedList, andPriorityQueueare not synchronized. For shared access, choose a concurrent collection such asConcurrentLinkedQueueor a blocking implementation such asArrayBlockingQueue.PriorityQueueis not synchronized; usePriorityBlockingQueuewhen 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
ArrayDequeserialization only captures elements, not internal state
Common Pitfalls / Anti-Patterns
poll()vsremove():poll()returnsnullon empty;remove()throwsNoSuchElementException. Usingremove()without checkingisEmpty()is a bug.peek()vselement(): Same distinction —peek()returnsnullon empty;element()throws- PriorityQueue is not sorted: The queue order is heap order, not sorted order. Only
peek()always returns the minimum. Iterating aPriorityQueuedoes NOT yield elements in sorted order. nullelements:PriorityQueueandArrayDequedo not allownullelements;LinkedListallowsnulladd()vsoffer(): Both insert if capacity allows, butadd()throwsIllegalStateExceptionon a full bounded queue whileoffer()returnsfalse
Quick Recap
Queuecommonly uses FIFO ordering, but each implementation defines its order;Dequesupports both ends andPriorityQueueorders by priorityArrayDequeis a useful default Deque; the Java SE API says it is likely faster thanLinkedListas a queue, but measure the workload if performance mattersPriorityQueueis a min-heap —peek()returns smallest; use a reversed comparator for max-heappoll()/offer()return null/false on failure;remove()/add()throw on failureArrayDeque,LinkedList, andPriorityQueueare not synchronized. Concurrent options includeConcurrentLinkedQueue,ConcurrentLinkedDeque, and theBlockingQueueimplementations.- Use a bounded
BlockingQueuewhen producers should wait, time out, or reject work as consumers fall behind; an unbounded queue does not provide that backpressure.
Interview Questions
Further Reading
- Oracle Queue Documentation — Ordering and Queue method contracts
- Oracle BlockingQueue Documentation — Blocking, timed, and bounded queue operations
- Oracle ConcurrentLinkedQueue Documentation — Thread-safe non-blocking queue
- Oracle Deque Documentation — Deque interface specification
- Baeldung: Java Queue Types — Comprehensive guide to Queue types and their characteristics
- PriorityQueue vs TreeMap — When to use each for ordered data
- ArrayList — ArrayList as a List vs Queue usage patterns
- LinkedList — LinkedList implements Queue/Deque
- HashSet — sets vs queues for different data structures
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.
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 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.