Queue
By Octavio Berlanga, on June 3rd, 2010.
A queue is a collection that yields its elements for processing.
Introduction
Most queues are in java.util.concurrent.
To add elements: boolean offer(E e)
To retrieve but not remove the head element: element() throws exception, peek()
To retrieve and remove the head element: remove() throws exception, poll()
PriorityQueue
Implements Queue
Located in java.util.
Ordering like that used in NavigableSet, based on implementation of the Comparable interface in its elements or by using the Comparator supplied to its constructor
Accomodates duplicates
ConcurrentLinkedQueue
Thread-safe.
FIFO ordering.
BlockingQueue
An interface that extends the Queue interface.
Designed for Producer-Consumer queues.
Add elements with offer(providing a timeout) or with put(waiting as long as necessary).
Remove elements with poll(providing a timeout) or take(waiting as long as necessary).
Remove multiple elements with drainTo().
Determine remaining capacity with remainingCapacity().
Reads and writes must take place within blocks synchronized on the same lock.
LinkedBlockingQueue
Implements BlockingQueue.
Thread-safe.
FIFO ordering.
Iterators are weakly consistent.
ArrayBlockingQueue
Implements BlockingQueue.
Thread-safe.
FIFO ordering.
Iterators are weakly consistent.
Uses a circular array
PriorityBlockingQueue
Implements BlockingQueue.
Thread-safe version of PriorityQueue.
DelayQueue
Implements BlockingQueue.
Thread-safe.
Ordering is based on the delay time. The element with the longest expired delay time will be at the head of the queue.
The elements of a DelayedQueue must implement the java.util.concurrent.Delayed interface.
SynchronousQueue
Elements cannot be added unless there is another thread ready to take them.
A mechanism to synchronize two threads.
Ensures there are enough consumer threads so that producers can add tasks without having to wait.
The elements of a DelayedQueue must implement the java.util.concurrent.Delayed interface.
Deque
Extends the Queue interface.
Allows insertions at either head or tail. It can act as a stack with LIFO ordering.
To insert at the head: addFirst(), Push(), offerFirst(), pollFirst().
To read at the head: peekFirst(), pollFirst(), getFirst(), removeFirst().
To insert at the tail: addLast(), offerLast(), pollLast().
To read at the tail: peekLast(), pollLast(), getLast(), removeLast().
ArrayDeque
Located in java.util.
Implements Deque
FIFO ordering
LinkedList
Located in java.util.
Implements Deque.
Use only if you also need random access of elements.
BlockingDeque
Extends the Deque interface.
LinkedBlockingDeque
Implements the BlockingDeque interface.
Queue Selection
If no thread safety is required, choose ArrayDeque for FIFO or PriorityQueue for priority ordering.