ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Queue & Deque
Book 1 · Volume II — Generics, Collections & Type System · Topic 4.5

Queue & Deque

PriorityQueue, ArrayDeque and BlockingQueue concepts

11 min readStage 1 · Foundations14 interview questions
Prerequisites
4.1 Collection Architecture
Covers
PriorityQueue · ArrayDeque · BlockingQueue concepts
Related
B2V4 (BlockingQueue implementations, executors) · Book 7 (message queues)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Queues hold elements awaiting processing. PriorityQueue removes the smallest element first according to a comparator; ArrayDeque is a resizable circular array usable as a FIFO queue or a LIFO stack; BlockingQueue (in java.util.concurrent) adds operations that wait when the queue is empty or full, coordinating producer and consumer threads.

2Why It Exists

Much of a service's work is not "look this up" but "deal with this next": requests waiting for a worker, jobs waiting for their time, nodes waiting to be visited. A List can hold them, but it says nothing about which element comes next, and removing from its front costs O(n). The queue interfaces make the processing order part of the type: FIFO, LIFO, or by priority.

Queue arrived in Java 5 with PriorityQueue and the java.util.concurrent blocking queues, which gave thread pools and producer-consumer code a standard hand-off point. Deque and ArrayDeque followed in Java 6 to replace Stack, a subclass of the synchronised Vector whose index methods let callers break the stack discipline, and LinkedList as a queue, which allocates a node per element.

3Core Concepts

PriorityQueue

An unbounded priority queue implemented as a binary min-heap in an array. peek returns the smallest element in O(1); offer and poll are O(log n); remove(Object) and contains are O(n). Ordering comes from natural ordering or a Comparator. Its iterator does not return elements in priority order — only repeated poll does. Null elements are not allowed; not thread-safe (PriorityBlockingQueue is the concurrent variant).

A binary heap stored in an array: the smallest element is always at index 0
Figure 1 — A binary heap stored in an array: the smallest element is always at index 0

ArrayDeque

A double-ended queue backed by a circular array with head and tail indexes, growing when full (doubling while it is small, then by 50%). All end operations are amortised O(1) and there is no per-element node object, so it is faster and smaller than LinkedList for queue and stack use and replaces the legacy synchronised Stack class. It does not allow null elements (null is used internally as the empty marker) and is not thread-safe.

ArrayDeque's circular buffer wraps around the end of the array
Figure 2 — ArrayDeque's circular buffer wraps around the end of the array

BlockingQueue concepts

BlockingQueue extends Queue with four styles of operation: throw (add/remove), return a special value (offer/poll), block (put/take), and time out (offer(e, timeout) / poll(timeout)). A bounded blocking queue provides back-pressure: producers wait when consumers fall behind, instead of filling memory. Implementations include ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, DelayQueue and SynchronousQueue; they underpin ThreadPoolExecutor (B2V4).

A bounded blocking queue between producers and consumers
Figure 3 — A bounded blocking queue between producers and consumers

4How It Works Internally

PriorityQueue stores a binary heap in an Object[]: the children of index i are at 2i + 1 and 2i + 2, its parent at (i - 1) / 2, and every parent is no larger than its children. offer appends at the end and sifts the element up while it is smaller than its parent; poll takes index 0, moves the last element to the root and sifts it down towards the smaller child (Figure 4). Both are O(log n). The array is ordered only along each root-to-leaf path, which is why iteration and toString show heap order, and why changing an element's priority in place breaks the heap.

PriorityQueue: offer sifts up, poll sifts down
Figure 4 — PriorityQueue: offer sifts up, poll sifts down

ArrayDeque keeps an array and two indexes, head and tail, that wrap around modulo the array length. addFirst decrements head, addLast writes at tail and increments it, so both ends are O(1) without moving elements. When the array is full it grows, doubling while it is small and by 50% after that, and copies the elements so that they are contiguous again. null cannot be stored, because an empty slot is null.

ArrayBlockingQueue adds a ReentrantLock and two conditions, notEmpty and notFull, around a circular array of fixed size: put waits on notFull and take on notEmpty, and each signals the other. LinkedBlockingQueue uses separate locks for its head and tail, so a producer and a consumer rarely contend, at the cost of a node per element; its default capacity is Integer.MAX_VALUE, which in practice means unbounded.

5APIs / Features / Syntax

Every queue operation exists in several forms that differ only in what happens when the operation cannot proceed. Choosing the form is choosing the failure behaviour:

OperationThrowsSpecial valueBlocksTimes out
Insert at the tailadd(e)offer(e): falseput(e)offer(e, time, unit)
Remove the headremove()poll(): nulltake()poll(time, unit)
Examine the headelement()peek(): null--
Deque: either endaddFirst, removeLast ...offerFirst, pollLast ...putFirst (BlockingDeque)offerFirst(e, time, unit)
Deque as a stackpush(e), pop()peek()--

The blocking and timed forms are declared by BlockingQueue and BlockingDeque and throw InterruptedException, so code that calls them inside a lambda or a Runnable must catch it and restore the interrupt flag, as Example 1 does. PriorityQueue takes a Comparator and an initial capacity; new ArrayBlockingQueue<>(capacity, fair) can grant waiting threads access in arrival order, at some cost in throughput.

6Practical Examples

Example 1 — Priority, deque and blocking queues in brief

Problem. Four recurring needs: keep the k largest values of a stream, schedule jobs by priority and due time, use a stack and a FIFO queue, and hand orders from one thread to another with back-pressure.

JAVAPriority, deque and blocking queues
// Top-k: keep the 3 largest amounts with a min-heap of size 3
PriorityQueue<BigDecimal> top = new PriorityQueue<>();
for (BigDecimal amount : amounts) {
    top.offer(amount);
    if (top.size() > 3) top.poll();              // drop the smallest
}

// Scheduling by priority then time
record Job(int priority, Instant due, String name) {}
PriorityQueue<Job> jobs = new PriorityQueue<>(
    Comparator.comparingInt(Job::priority).thenComparing(Job::due));

// Stack and queue with ArrayDeque
Deque<Character> stack = new ArrayDeque<>();
stack.push('(');  stack.pop();
Queue<String> fifo = new ArrayDeque<>();
fifo.offer("a");  fifo.poll();

// Producer–consumer with back-pressure
BlockingQueue<Order> inbox = new ArrayBlockingQueue<>(1_000);
Thread producer = Thread.ofVirtual().start(() -> {
    try {
        for (Order o : incoming()) inbox.put(o);     // waits when full
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
Thread consumer = Thread.ofVirtual().start(() -> {
    try {
        while (true) process(inbox.take());          // waits when empty
    } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});

Example 2 — Mini program: a job scheduler on a PriorityQueue

Problem. Jobs arrive with a priority (1 is most urgent) and a due time. The scheduler must run them by priority and, within a priority, by due time, and an operator must be able to raise the priority of a waiting job.

JAVAJobScheduler.java
import java.time.Instant;
import java.util.*;
 
public class JobScheduler {
    record Job(int priority, Instant due, String name) { }      // 1 = most urgent
 
    public static void main(String[] args) {
        Instant t = Instant.parse("2026-11-10T08:00:00Z");
        PriorityQueue<Job> jobs = new PriorityQueue<>(
                Comparator.comparingInt(Job::priority).thenComparing(Job::due));
        jobs.offer(new Job(3, t.plusSeconds(60), "rebuild-index"));
        jobs.offer(new Job(1, t.plusSeconds(300), "refund-4711"));
        jobs.offer(new Job(2, t.plusSeconds(30), "send-invoices"));
        jobs.offer(new Job(1, t.plusSeconds(120), "refund-4712"));
        jobs.offer(new Job(3, t.plusSeconds(10), "purge-temp"));
 
        System.out.println("peek       " + jobs.peek().name());
        System.out.println("iterator   " + jobs.stream().map(Job::name).toList());
 
        // raise a priority: remove and offer a new job, never mutate in place
        Job purge = jobs.stream().filter(j -> j.name().equals("purge-temp"))
                        .findFirst().orElseThrow();
        jobs.remove(purge);                                      // O(n)
        jobs.offer(new Job(2, purge.due(), purge.name()));       // O(log n)
 
        System.out.println("poll order");
        while (!jobs.isEmpty()) {
            Job j = jobs.poll();
            System.out.println("  P" + j.priority() + " " + j.name());
        }
    }
}
OUTPUT
peek       refund-4712
iterator   [refund-4712, refund-4711, send-invoices, rebuild-index, purge-temp]
poll order
  P1 refund-4712
  P1 refund-4711
  P2 purge-temp
  P2 send-invoices
  P3 rebuild-index

Why it behaves this way. peek shows the true head, refund-4712: priority 1 and due earlier than refund-4711. The iterator shows the heap array, which is not sorted: purge-temp comes last although it is due before rebuild-index. The priority change removes the job, an O(n) search, and offers a new record, which sifts into place; mutating a field of a queued job would have left it in the wrong position. Only the poll loop yields jobs in priority order.

Example 3 — ArrayDeque as a stack: checking brackets

Problem. A template engine must report unbalanced or mismatched brackets with their positions. Each closing bracket must match the most recent unclosed opening one, which is a last-in, first-out rule.

JAVABracketCheck.java
import java.util.*;
 
public class BracketCheck {
    static final Map<Character, Character> OPEN_FOR =
            Map.of(')', '(', ']', '[', '}', '{');
 
    static String check(String s) {
        Deque<Integer> open = new ArrayDeque<>();   // positions of open brackets
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                open.push(i);
            } else if (OPEN_FOR.containsKey(c)) {
                if (open.isEmpty()) return "unexpected '" + c + "' at " + i;
                int at = open.pop();
                if (s.charAt(at) != OPEN_FOR.get(c))
                    return "'" + s.charAt(at) + "' at " + at
                         + " closed by '" + c + "' at " + i;
            }
        }
        if (open.isEmpty()) return "balanced";
        return "unclosed '" + s.charAt(open.peek()) + "' at " + open.peek();
    }
 
    public static void main(String[] args) {
        for (String s : List.of("{order: [items(1), items(2)]}",
                "{order: [items(1}]", "total(x))", "{{customer}")) {
            System.out.printf("%-30s %s%n", s, check(s));
        }
    }
}
OUTPUT
{order: [items(1), items(2)]}  balanced
{order: [items(1}]             '(' at 14 closed by '}' at 16
total(x))                      unexpected ')' at 8
{{customer}                    unclosed '{' at 0

Why it behaves this way. push and pop work at the head of the deque, so pop always returns the latest open bracket. The stack stores positions rather than characters, which lets the message point at both ends of a mismatch. An empty stack at a closing bracket, or a non-empty stack at the end, are the other two errors. Stack would work too, but it synchronises every call and lets code read or insert in the middle.

Example 4 — A bounded queue between a fast producer and a slow consumer

Problem. Show the four failure behaviours on a full queue, then run a producer that creates 20 orders as fast as it can against a consumer that needs 5 ms per order, with a queue of 4 between them.

JAVABoundedPipeline.java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
 
public class BoundedPipeline {
    static final String DONE = "DONE";                          // poison pill
 
    public static void main(String[] args) throws Exception {
        BlockingQueue<String> full =
                new ArrayBlockingQueue<>(2, false, List.of("a", "b"));
        try {
            full.add("c");
        } catch (IllegalStateException e) {
            System.out.println("add   -> IllegalStateException");
        }
        System.out.println("offer -> " + full.offer("c"));
        System.out.println("offer(50 ms) -> "
                + full.offer("c", 50, TimeUnit.MILLISECONDS));
 
        BlockingQueue<String> inbox = new ArrayBlockingQueue<>(4);
        AtomicInteger maxSeen = new AtomicInteger();
        List<String> processed = Collections.synchronizedList(new ArrayList<>());
        Thread consumer = Thread.ofPlatform().start(() -> {
            try {
                for (String o = inbox.take(); !o.equals(DONE); o = inbox.take()) {
                    Thread.sleep(5);                            // slow work
                    processed.add(o);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        long blockedNanos = 0;
        for (int i = 1; i <= 20; i++) {
            long t0 = System.nanoTime();
            inbox.put("order-" + i);                // waits while full
            blockedNanos += System.nanoTime() - t0;
            maxSeen.accumulateAndGet(inbox.size(), Math::max);
        }
        inbox.put(DONE);
        consumer.join();
        List<String> sent = IntStream.rangeClosed(1, 20)
                                     .mapToObj(i -> "order-" + i).toList();
        System.out.println("processed " + processed.size()
                + ", in order " + processed.equals(sent));
        String waited = blockedNanos > 10_000_000 ? "> 10 ms" : "<= 10 ms";
        System.out.println("max queued " + maxSeen.get() + " of 4,"
                + " producer waited " + waited);
    }
}
OUTPUT(the last line can vary)
add   -> IllegalStateException
offer -> false
offer(50 ms) -> false
processed 20, in order true
max queued 4 of 4, producer waited > 10 ms
What to do when a bounded queue is full
Figure 5 — What to do when a bounded queue is full

Why it behaves this way. On the full two-element queue, add throws, offer returns false at once and the timed offer returns false after 50 ms. In the pipeline, put blocks the producer whenever four orders are waiting, so it can never get more than four ahead: memory stays bounded and the producer runs at the consumer's speed. A single consumer taking from a FIFO queue processes the orders in order, and the DONE pill ends it cleanly. Figure 5 shows the other policies a service can choose when blocking is not acceptable, for example on a request thread.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Iterating a PriorityQueue and expecting sorted orderThe iterator walks the heap array; output looks almost sorted in tests and is wrong in productionpoll in a loop, or sort a copy: new ArrayList<>(pq).sort(cmp)
Stack or LinkedList as a stack or queueStack locks on every call and exposes index methods; LinkedList allocates a node per elementArrayDeque
Unbounded LinkedBlockingQueue (the default constructor) in executorsOverload turns into queueing delay and then OutOfMemoryError, with no early signalA bounded queue with an explicit rejection policy, and a metric for its size
Mutating an element's priority while it is in a PriorityQueueThe heap is not re-ordered; poll returns elements in the wrong orderRemove, change (or create a new element) and re-offer (Example 2)
Adding null to ArrayDeque or PriorityQueueNullPointerException: null is the empty-slot marker, and poll uses null for "empty"Use Optional or a sentinel object
Ignoring or swallowing InterruptedException from put and takeThe snippet does not compile, or a swallowed interrupt keeps a thread running after shutdownCatch it, restore the flag with Thread.currentThread().interrupt() and exit

8Performance & Production Considerations

Queues are where overload shows up. Every in-process queue between stages should be bounded and monitored (size, wait time), with a clear policy when full: block, reject, drop oldest, or shed load. Unbounded queues convert overload into latency growth and eventually OutOfMemoryError.

9Architecture & Design Considerations

In-process queues are the small-scale version of message brokers (Kafka, RabbitMQ, SQS — Book 7): they decouple producers from consumers and absorb bursts. The same design questions apply at both scales — bounding and back-pressure, ordering guarantees, priority, what happens to queued work on shutdown or crash. In-process queues lose their contents when the JVM stops; durable work belongs in a broker or database.

10Interview Questions & Answers

Q1L1 · BasicConcept

What data structure does PriorityQueue use?

A binary min-heap stored in an array; the smallest element according to the comparator is always at the head.

Q2L2 · IntermediateTrade-off

Why is ArrayDeque preferred over Stack and LinkedList?

It is a compact circular array with O(1) amortised end operations, no per-element nodes and no synchronisation overhead, making it faster and smaller than LinkedList and the legacy synchronised Stack.

Q3L2 · IntermediateConcept

What is the difference between offer/poll and put/take in BlockingQueue?

offer and poll return immediately with false or null if the queue is full or empty (or wait up to a timeout in their timed forms). put and take block until space or an element is available.

Q4L3 · Senior EngineerCode

How would you find the k largest elements of a large stream efficiently?

Keep a min-heap PriorityQueue of size k: add each element and poll when the size exceeds k. Cost is O(n log k) time and O(k) memory.

Q5L3 · Senior EngineerScenario

Why is an unbounded queue in a thread pool dangerous?

When producers outpace consumers, the queue grows without limit, latency rises unobserved and memory eventually runs out. A bounded queue with a rejection or back-pressure policy surfaces overload early and predictably.

Q6L4 · Technical ArchitectTrade-off

When would you use an in-process BlockingQueue versus a message broker?

In-process queues suit decoupling stages within one JVM where losing queued work on restart is acceptable. When work must survive crashes, be shared across instances, be replayed or scale independently, a durable broker is required.

Q7L1 · BasicConcept

What is the difference between poll and remove on a Queue?

Both remove and return the head. On an empty queue, remove() throws NoSuchElementException and poll() returns null. Use poll when an empty queue is a normal condition, as in a worker loop, and remove when emptiness would be a bug. The same pairing exists for add and offer, and for element and peek.

Q8L2 · IntermediateCode

What does this program print?

JAVAHeapQuiz.java
import java.util.*;
 
public class HeapQuiz {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(5, 1, 4, 2, 3));
        System.out.println(pq);
        StringBuilder polled = new StringBuilder();
        while (!pq.isEmpty()) polled.append(pq.poll()).append(' ');
        System.out.println(polled.toString().trim());
 
        Deque<String> d = new ArrayDeque<>();
        d.push("a"); d.push("b"); d.offer("c");
        System.out.println(d.pop() + d.poll() + d.pollLast());
    }
}

It prints [1, 2, 4, 5, 3], then 1 2 3 4 5, then bac. toString shows the heap array, which is ordered only along each path from the root: 1 is at the root, but 5 comes before 3, because 5 and 3 are both children of 2 at indexes 3 and 4. Repeated poll gives sorted order. In the deque, push adds at the head and offer at the tail, so the deque is [b, a, c]; pop and poll both take the head, and pollLast the tail.

Q9L3 · Senior EngineerInternals

Why are offer and poll O(log n) on a PriorityQueue, but remove(Object) O(n)?

offer and poll change one position and restore the heap property along a single path, which is at most log2(n) levels long. remove(Object) must first find the element, and a heap has no order that guides a search, so it scans the array; the removal itself is then another O(log n) sift. When items are often cancelled, mark them as cancelled and skip them on poll, or use a TreeSet with a tie-breaker.

Q10L3 · Senior EngineerTricky

Why does ArrayDeque reject null elements when LinkedList accepts them?

Because ArrayDeque uses null to mark an empty slot in its circular array, and because poll and peek return null to signal an empty deque. A stored null would be indistinguishable from both. LinkedList stores elements in nodes, so it can hold null, but a null in a queue is still ambiguous for every caller of poll. Model "no value" explicitly instead.

Q11L3 · Senior EngineerScenario

Response times of a service grow from 50 ms to 20 s during a traffic spike, yet CPU stays at 60% and no errors are logged. The executor was created with Executors.newFixedThreadPool(50). What is happening, and what do you change?

newFixedThreadPool uses an unbounded LinkedBlockingQueue. When requests arrive faster than 50 threads can serve them, they wait in the queue; nothing is rejected, so no error appears, and latency grows with the queue length until clients time out or memory runs out. CPU can stay moderate because the threads are waiting on I/O. Create the ThreadPoolExecutor with a bounded ArrayBlockingQueue, a rejection policy such as returning 503 or CallerRunsPolicy, and metrics for queue size and wait time; then size the pool from the measured service time.

Q12L4 · Technical ArchitectDesign

Design the hand-off between an HTTP layer receiving 5,000 events per second and a database writer that handles 4,000 per second on average with bursts.

A bounded in-memory queue sized for the expected burst, say a few seconds of excess, absorbs short peaks. The writer drains it in batches, using drainTo to collect up to N events per transaction, which also raises its throughput. When the queue is full, the HTTP layer must not block its request threads: it uses a timed offer and answers 429 or 503 so that clients back off. Because the queue is lost on a crash, events that must not be lost go to a durable broker first. Monitor queue depth, wait time and rejections.

Q13L5 · Solution ArchitectTrade-off

Should a platform standardise on in-process queues or on a message broker for asynchronous work between components of the same service?

In-process queues are fast, simple and free of infrastructure, and they keep ordering and back-pressure easy to reason about. But they lose their contents on every deploy or crash, they cannot be shared across instances, and they hide backlog inside one JVM. A broker adds latency, operations and cost, and gives durability, replay, independent scaling and visibility. A sound standard is in-process, bounded queues for work that can be recomputed or dropped, and a broker, possibly fed through an outbox table, for work that is a business commitment (Book 7).

Q14L5 · Solution ArchitectScenario

After a deploy, a fraction of orders that were "accepted" were never processed. The service queues them in an ArrayBlockingQueue consumed by worker threads. What went wrong, and how do you fix it?

The queue lives in the JVM: orders that were accepted, answered with 202, and still queued when the old instance stopped were lost, and so were orders in flight in the workers. Shutdown probably stopped the executor without draining. Short term, stop accepting on shutdown, drain the queue and wait for the workers within the termination grace period. Properly, an accepted order must be durable before the reply, so write it to the database or a broker first and let the queue only hold references to work that can be re-read after a restart.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • PriorityQueue: array-based min-heap, O(log n) offer/poll, iterator not ordered.
  • ArrayDeque: the default queue and stack.
  • BlockingQueue: blocking/timed operations; bounded queues give back-pressure.
  • Bound and monitor every queue between processing stages.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.