Java Reference
In-Depth Information
Returns and removes the head of this queue, waiting if neces-
sary for the queue to be non-empty.
public E
poll(long time, TimeUnit unit)
throws InterruptedException
Returns and removes the head of this queue, waiting if neces-
sary up to the specified waiting time for the queue to be non-
empty. Returns the head of the queue, or
null
if the specified
waiting time elapsed before an element became available.
As these are all potentially blocking operations. They support cancel-
lation by throwing an
InterruptedException
in response to the current
thread being interrupted.
You specify the waiting times with a
long
to indicate the time, and a
value of the enum
java.util.concurrent.TimeUnit
to indicate the units.
The
enum
TimeUnit
has
the
constants
NANOSECONDS
,
MICROSECONDS
,
MILLISECONDS
, and
SECONDS
.
A
BlockingQueue
may be capacity constrained. The
remainingCapacity
method returns the number of elements that can be put in the queue
without causing blockingbut note that if multiple threads are using the
queue it doesn't guarantee how many elements an individual thread
may be able to add without blocking. If there is no inherent limit
In-
teger.MAX_VALUE
is returned. If there is a capacity limit then
Collec-
tion.add
will throw
IllegalStateException
if the element cannot be added.
The
drainTo
method takes a collection and attempts to transfer all the
elements of this queue into the given collection. The number of elements
transferred is returned. An overloaded form of
drainTo
takes an addi-
tional
int
parameter that limits the maximum number of elements to
transfer. This operation is provided as an alternative to repeated polling
of the queue because some implementations will be able to implement it
very efficientlyeven atomically. However, the guarantees of this method
are somewhat loose: It is possible that if an error occurs when an ele-
ment is added to the target collection, the element may end up in one,
neither, or both collections!