Queues in Java 5:
the Queue interface

Java 5 introduces several queue implementations to the Collections framework. Queue implementations firstly share a new Queue interface, which has several methods for accessing the head and tail of the queue. Recall that items are in general always placed on the end or "tail" of the list, and always read from the beginning or "head" of the list. (An exception that we'll see is that in the case of priority queues, there's no actual "tail", although the notion still more or less applies.)

OperationThrows exception
if not possible
Returns value
if not possible
Add item to tailadd()offer()
Remove item from headremove()poll()
"Peek" item at headelement()peek()
Methods specified by the Java Queue interface

Types of Queues

Java provides Queue implementations depending on a few key criteria:

As of Java 6, the various queue classes are as follows:

Queue implementations as of Java 6
Blocking?Other criteriaBoundNon-bound
BlockingNoneArrayBlockingQueueLinkedBlockingQueue
Priority-based PriorityBlockingQueue
Delayed DelayQueue
Non-blockingThread-safe ConcurrentLinkedQueue
Non thread-safe LinkedList
Non thread-safe, priority-based PriorityQueue

One further type of queue not included above is the SynchronousQueue, which is effectively a zero-length queue (so that a thread adding an item to the queue will block until another thread removes the item).

Blocking queues

In general, the most interesting queue implementations are the various blocking queues, which allow efficient concurrent access and are useful for coordinating objects between threads, particularly in the so-called producer-consumer pattern. In Java, all blocking queue implementations implement the BlockingQueue interface, which we look at next.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.