Understanding Java Queues: Types, Blocking vs Non‑Blocking, and Practical Examples
This article explains what a queue is, classifies Java queue implementations—including blocking, non‑blocking, and double‑ended queues—provides detailed descriptions of each type, and offers code snippets and usage scenarios to help developers choose the right queue for their applications.
What Is a Queue?
A queue is a linear data structure that restricts operations to inserting elements at the rear (enqueue) and removing elements from the front (dequeue), following the First‑In‑First‑Out (FIFO) principle. In Java, the LinkedList class implements the Queue interface, effectively acting as a queue.
How Java Queues Are Categorized
Java queues can be classified along several dimensions:
Blocking vs. non‑blocking
Bounded vs. unbounded
Functional categories such as priority queues, ordinary queues, double‑ended queues, and delayed queues
These categories are illustrated in the diagram below.
Common Java Queue Implementations
1. Blocking Queues
Blocking queues pause producer or consumer threads when the queue is full or empty, helping to balance throughput.
Typical blocking queues include seven major classes:
ArrayBlockingQueue : A bounded queue backed by an array.
ArrayBlockingQueue<String> fairQueue = new ArrayBlockingQueue<>(1000, true);LinkedBlockingQueue : A linked‑list based bounded queue with default and maximum capacity of Integer.MAX_VALUE.
PriorityBlockingQueue : An unbounded queue that orders elements by priority rather than FIFO.
DelayQueue : An unbounded queue of Delayed elements that become available only after their delay expires. Common uses include cache expiration and timed task scheduling.
SynchronousQueue : Holds at most one element; each put must wait for a corresponding take.
LinkedTransferQueue : An unbounded transfer queue with additional tryTransfer and transfer methods.
LinkedBlockingDeque : A double‑ended blocking queue allowing insertion and removal at both ends, reducing contention in multi‑threaded scenarios.
2. Non‑Blocking Queues
Non‑blocking queues never block; if a queue is full, the operation fails immediately.
ConcurrentLinkedQueue : An unbounded, thread‑safe, single‑direction queue implemented with CAS.
ConcurrentLinkedDeque : An unbounded, thread‑safe double‑ended queue implemented with CAS.
PriorityQueue : A non‑thread‑safe, array‑backed priority queue.
3. Double‑Ended Queues (Deque)
A Deque (double‑ended queue) supports insertion and removal at both the front and rear, providing greater flexibility for certain algorithms.
Architect Chen
Sharing over a decade of architecture experience from Baidu, Alibaba, and Tencent.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
