The BlockingQueue Interface – Concurrency: Part II

The BlockingQueue<E> Interface

The java.util.concurrent.BlockingQueue interface extends the java.util.Queue interface, as shown in Figure 23.6. Compared to the operations shown for the Queue interface in Table 23.7, the BlockingQueue interface provides new insert and remove operations that can block or can time out—shown in the two rightmost columns in Table 23.13. Classes that implement the BlockingQueue interface are shown in Table 23.11, where general-purpose queues are listed at the top, down to more specialized thread-safe queues. The LinkedBlockingQueue class represents the all-round queue of choice in most cases.

Table 23.13 Selected Methods in the BlockingQueue Interface

OperationThrows exceptionReturns special valueBlocksTimes out
Insert at the tailadd(e) can throw IllegalArgument-Exceptionoffer(e) returns true or falseput(e) blocks if no spaceoffer(e, time, unit) waits if necessary for specified time if no space
Remove from the headremove() can throw NoSuchElement-Exceptionpoll() returns head element or nulltake() blocks if emptypoll(time, unit) waits if necessary for specified time for head element, and returns null if no element becomes available
Examine element at the headelement() can throw NoSuchElement-Exceptionpeek() returns head element or nullNot applicableNot applicable

The TransferQueue<E> Interface

The TransferQueue interface extends the BlockingQueue interface to provide queues where producers wait for consumers to receive elements (Figure 23.6). The interface defines additional methods to utilize this property.

Click here to view code image

void transfer(E e)
boolean tryTransfer(E e)
boolean tryTransfer(E e, long timeout, TimeUnit unit)

The first method transfers the element to a consumer, waiting if necessary to do so.

The second method transfers the element to a waiting consumer immediately, if possible. It returns true if the element was transferred; otherwise, it returns false.

The third method transfers the element to a consumer if it is possible to do so before the timeout elapses. It returns true if successful, and false if the specified waiting time elapses before completion, in which case the element is not left enqueued.

Click here to view code image

boolean hasWaitingConsumer()
int getWaitingConsumerCount()

The first method returns true if there is at least one consumer waiting to receive an element via BlockingQueue.take() or a timed poll.

The second method returns an estimate of the number of consumers waiting to receive elements via BlockingQueue.take() or a timed poll.

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>