Java Reference
In-Depth Information
Removing elements from queues
remove()
In addition to the
Collection.remove()
method, which removes a specified
element from the queue, the
Queue
interface defines a no-argument version of
remove()
that removes and returns the element at the head of the queue. If the
queue is empty, this method throws a
NoSuchElementException
.
poll()
This
Queue
method removes and returns the element at the head of the queue,
like
remove()
does but returns
null
if the queue is empty instead of throwing
an exception.
BlockingQueue
defines a timeout version of
poll()
that waits up to a specified
amount of time for an element to be added to an empty queue.
take()
This
BlockingQueue
method removes and returns the element at the head of
the queue. If the queue is empty, it blocks until some other thread adds an ele‐
ment to the queue.
drainTo()
This
BlockingQueue
method removes all available elements from the queue
and adds them to a specified
Collection
. It does not block to wait for elements
to be added to the queue. A variant of the method accepts a maximum number
of elements to drain.
Querying
In this context, querying refers to examining the element at the head without
removing it from the queue.
element()
This
Queue
method returns the element at the head of the queue but does not
remove that element from the queue. If the queue is empty, it throws
NoSuchE
lementException
.
peek()
This
Queue
method is like
element
but returns
null
if the queue is empty.
When using queues, it is usually a good idea to pick one par‐
ticular style of how to deal with a failure. For example, if you
want operations to block until they succeed, then choose
put()
and
take()
. If you want to examine the return code of a
method to see if the queue operation suceeded, then
offer()
and
poll()
are an appropriate choice.