BlockingQueue

BlockingQueue is an interface that extends the standard Queue interface with methods that are suitable to be used by multithread applications. Any implementation of this interface provides methods that allow different threads to put element into the queue, pull elements off the queue, and wait for elements that are in the queue.

When there is a new element that is to be stored in the queue, you can add it, offer it, or put it. These are the name of the methods that store elements and they do the same thing, but a bit differently. The add element throws an exception if the queue is full and there is no room for the element. The offer element does not throw exception but returns either true or false, based on the success. If it can store the element in the queue, it returns true. There is also a version of offer that specifies a timeout. That version of the method waits, and returns only false if it cannot store the value into the queue during the period. The put element is the dumbest version; it waits until it can do its job.

When talking about available room in a queue, do not get puzzled and mix it with general Java memory management. If there is no more memory, and the garbage collector can also not release any, you will certainly get OutOfMemoryError. Exception is thrown by add, and false is returned by offer, when the queue limits are reached. Some of the BlockingQueue implementations can limit the number of elements that can be stored at a time in a queue. If that limit is reached, then the queue is full and cannot accept more elements.

Fetching elements from a BlockingQueue implementation also has four different ways. In this direction, the special case is when the queue is empty. In that case, remove throws an exception instead of returning the element, poll returns null if there is no element, and take just waits until it can return an element.

Finally, there are two methods inherited from the interface Queues that do not consume the element from the queue only look at. The element return the head of the queue and throws an exception if the queue is empty, and peek returns null if there is no element in the queue. The following table summarizes the operations borrowed from the documentation of the interface:

Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.12.34