Java Reference
In-Depth Information
Other orderings are also possible: a
priority queue
orders its elements according to
an external
Comparator
object, or according to the natural ordering of
Comparable
elements. Unlike a
Set
,
Queue
implementations typically allow duplicate elements.
Unlike
List
, the
Queue
interface does not define methods for manipulating queue
elements at arbitrary positions. Only the element at the head of the queue is avail‐
able for examination. It is common for
Queue
implementations to have a fixed
capacity: when a queue is full, it is not possible to add more elements. Similarly,
when a queue is empty, it is not possible to remove any more elements. Because full
and empty conditions are a normal part of many queue-based algorithms, the
Queue
interface defines methods that signal these conditions with return values rather than
by throwing exceptions. Specifically, the
peek()
and
poll()
methods return
null
to
indicate that the queue is empty. For this reason, most
Queue
implementations do
not allow
null
elements.
A
blocking queue
is a type of queue that defines blocking
put()
and
take()
meth‐
ods. The
put()
method adds an element to the queue, waiting, if necessary, until
there is space in the queue for the element. And the
take()
method removes an ele‐
ment from the head of the queue, waiting, if necessary, until there is an element to
remove. Blocking queues are an important part of many multithreaded algorithms,
and the
BlockingQueue
interface (which extends
Queue
) is defined as part of the
java.util.concurrent
package.
Queues are not nearly as commonly used as sets, lists, and maps, except perhaps in
certain multithreaded programming styles. In lieu of example code here, we'll try to
clarify the different possible queue insertion and removal operations.
Adding elements to queues
add()
This
Collection
method simply adds an element in the normal way. In boun‐
ded queues, this method may throw an exception if the queue is full.
offer()
This
Queue
method is like
add()
but returns
false
instead of throwing an
exception if the element cannot be added because a bounded queue is full.
BlockingQueue
defines a timeout version of
offer()
that waits up to a speci‐
fied amount of time for space to become available in a full queue. Like the basic
version of the method, it returns
true
if the element was inserted and
false
otherwise.
s
a
put(
This
BlockingQueue
method blocks: if the element cannot be inserted because
the queue is full,
put()
waits until some other thread removes an element from
the queue, and space becomes available for the new element.