A PriorityBlockingQueue in Java implements the BlockingQueue interface and supports the features of a PriorityQueue. So, what’s a BlockingQueue?
Following holds true for any implementation of a BlockingQueue:
A PriorityBlockingQueue is an unbounded concurrent blocking queue present in java.util.concurrent package. It doesn’t allow null values.
The elements in a PriorityBlockingQueue are polled based on their priority. By default, an object’s natural ordering is considered to be its priority. We can override the default priority by either implementing Comparable interface or providing a Comparator.
Let’s say we have a PriorityBlockingQueue with two or more elements having the maximum priority. In that case, polling will randomly return one among them.
We can use one of the following constructors to instantiate a PriorityBlockingQueue:
//creates an empty PriorityBlockingQueue with capacity of 11 PriorityBlockingQueue() //creates a PriorityBlockingQueue containing elements of c PriorityBlockingQueue(Collection c) //uses given initialCapacity to instantiate a PriorityBlockingQueue PriorityBlockingQueue(int initialCapacity) /*creates an empty PriorityBlockingQueue with given initialCapacity * which orders its elements using given comparator */ PriorityBlockingQueue(int initialCapacity, Comparator comparator)
Let’s quickly look at the methods we can use when working with a PriorityBlockingQueue:
To insert an element in a PriorityBlockingQueue, we can use any of the following methods:
PriorityBlockingQueue<Integer> pbq = new PriorityBlockingQueue<>(); pbq.add(4); //Or pbq.offer(1); //Or pbq.put(8);
Since a PriorityBlockingQueue is unbounded, all of them behave the same way. In other words, offer(e) will never return false and put(e) will never block the operation.
We can remove an element in a PriorityBlockingQueue in one of the following ways:
//Assuming pbq has [1, 4, 8] as its elements boolean result = pbq.remove(4); //true System.out.println(pbq); [1, 8]
//Assuming pbq has [1, 4, 8] as its elements int polledItem = pbq.poll(); //1 System.out.println(pbq); [4, 8]
The other commonly used methods include:
//Assuming pbq has [1, 4, 8] as its elements int item = pbq.peek(); //1 System.out.println(pbq); [1, 4, 8]
In this quick tutorial, we explored what a PriorityBlockingQueue is and how to use it. It is a thread-safe implementation and blocks the polling until an element becomes available.