javapriority-queueblockingqueue

Java PriorityBlockingQueue blocking behavior


From the docs I see, that the take() method blocks until an element becomes available.
Is there any other scenario when it could block?

What I mean is, is there a possible scenario, when the queue is not empty, but despite that, calling take() blocks for some reason.

Please tell me, if anyone has knowledge about some scenario like this.


Solution

  • Is there any other scenario when it could block?

    By my reading of the code (Java 11 version) take() should only block if the queue is empty when the call is made.

    But that doesn't imply that a take() call will immediately unblock when the queue becomes non-empty. Indeed, if two or more threads are calling take() at the same time, it is conceivable that some threads will "starve" because the arriving elements are consistently being delivered to other waiting threads. (The PriorityBlockingQueue uses ReentrantLock instances to coordinate the producers and consumers, but these are not created as fair locks.)

    Another scenario involves faulty Comparable or Comparator implementations. When the queue is or becomes non-empty, take() calls an internal dequeue method which in turn uses the Comparable or Comparator interface to sift the queue. If your Comparable or Comparator code could itself block, that would block the current take() call and all future take() calls.


    Having said that, you also need to consider the most obvious explanation; i.e. that take() is blocking because the queue really is empty.