[concurrency-interest] PriorityBlockingQueue put() operation

Tim Peierls tim at peierls.net
Sat Nov 7 15:45:46 EST 2009


On Sat, Nov 7, 2009 at 3:01 PM, Michael Spiegel <michael.m.spiegel at gmail.com
> wrote:

> Hi,
>
> I apologize if this question has been answered before of if the answer
> is trivially obvious.  The documentation for
> java.util.concurrent.PriorityBlockingQueue states that the put(E e)
> method will never block, and such claims are not made about the add(E
> e) method.  The method bodies for both methods are identical, ignoring
> the fact that one method returns boolean and the other doesn't return
> a value.  The methods body is an invocation to the offer(E e) method.
> I believe that offer() is a blocking method, since it locks the
> ReentrantLock around the data structure.  So is put() a blocking
> method? I must be missing something obvious.
>

Simply holding a lock doesn't necessarily make a method into a blocking
method. A blocking method conventionally has "throws InterruptedException"
in its signature, a sign to calling code that the method might wait (i.e.,
block) until some condition holds, and that the caller should be prepared to
handle the possibility of interruption while it waits.

The add() method comes from java.util.Collection; it's not a blocking
method. The (untimed) offer() method comes from java.util.Queue; it isn't a
blocking method, either.

BlockingQueue.put() *is* generally a blocking method; it waits for the queue
to have room for the new element and throws InterruptedException if
interrupted while waiting. But since PriorityBlockingQueue is unbounded, it
always has room, so it never has to wait and there is no need for it to
throw InterruptedException. So PriorityBlockingQueue.put() is not a blocking
method.

--tim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://cs.oswego.edu/pipermail/concurrency-interest/attachments/20091107/cb437e1f/attachment.html>


More information about the Concurrency-interest mailing list