PriorityBlockingQueue in Java

PriorityBlockingQueue is an implementation of the BlockingQueue, Which is backed by the Array Based binary heap Data Structure. PriorityBlockingQueue can be initialized with and without the specified limit.

If you do not specify the limit then default limit will be 11 , the following are constructors of the PriorityBlockingQueue.


  • PriorityBlockingQueue()
  • PriorityBlockingQueue(int initialCapacity)
  • PriorityBlockingQueue(int initialCapacity,Comparator<? super E> comparator)

If the added elements size reached to the initialCapacity, then PriorityBlockingQueue size will grow dynamically and will not throw any exceptions.

Elements which are adding to the PriorityBlockingQueue should implement Comparable or Comparator interface.

In case elements are implemented Comparator interface then it should be specified in the PriorityBlockingQueue Constructor.

Fetching of the elements will be done based on the implementation of Comparable or Comparator interfaces

The following are the most commonly used methods in the PriorityBlockingQueue.


Insert Operation

  • add(e) If this operation is not possible immediately then an exception will be thrown.
  • offer(e) If this operation is not possible immediately then it will return false otherwise true.
  • put(e) This operation will wait until it gets success in other words it will block the current thread until operation gets success.
  • offer(e, time, unit) This operation is not possible immediately then it will until the specified time limit for success otherwise it will returns false

Remove Operation

  • remove(Object e) If the queue contains the element e then it will remove that element and return true otherwise return false. If the Object e is not compatible with Queue will lead to an exception
  • poll() It will retrieve and removes the head of the queue, in case Queue is empty return null.
  • take() It will retrieve and removes the head of the queue, in case Queue is empty thread will wait until the element becomes available.
  • poll(time, unit) It will retrieve and removes the head of the queue, in case Queue is empty will wait until the specified time exhausted

Examine Operation

  • element() :-It will retrieve and will not remove the head of the queue, in case Queue is empty will lead to an exception
  • peek():- It will retrieve and will not remove the head of the queue, in case Queue is empty returns null.

  • PriorityBlockingQueue Example in Java


    <-PREV NEXT->