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
Operation | Throws exception | Returns special value | Blocks | Times out |
Insert at the tail | add(e) can throw IllegalArgument-Exception | offer(e) returns true or false | put(e) blocks if no space | offer(e, time, unit) waits if necessary for specified time if no space |
Remove from the head | remove() can throw NoSuchElement-Exception | poll() returns head element or null | take() blocks if empty | poll(time, unit) waits if necessary for specified time for head element, and returns null if no element becomes available |
Examine element at the head | element() can throw NoSuchElement-Exception | peek() returns head element or null | Not applicable | Not 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.
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.
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.