PriorityBlockingQueue in Java
- PriorityBlockingQueue uses same unbounded blocking queue that uses the same ordering rules as PriorityQueue and supplies blocking retrieval operations.
- PriorityBlockingQueue does not allow null values to be added.
- PriorityBlockingQueue also uses natural sorting order and will not permit non-comparable objects to be insert which will result in ClassCastException exception.
- PriorityBlockingQueue uses methods as same as PriorityQueue class except drainTo() and remainingCapacity() methods.
- drainTo(Collection<? super E> c) method used remove all available elements from the queue and adds them to the given collection.
- drainTo(Collection<? super E> c, int maxElements) method used to remove at most the given number of available elements from the queue and adds them to the given collection.
- remainingCapacity() method used to return Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.
- Method iterator() is not guaranteed to traverse the elements of PriorityBlockingQueue in any particular order. We can see this in below example.
Difference Between PriorityBlockingQueue and PriorityQueue:
- PriorityQueue is not thread safe, where as PriorityBlockingQueue is thread safe.
- PriorityBlockingQueue introduced in JDK 5 which added with concurrent package.
Now lets see simple example for PriorityBlockingQueue and how its working under multi-threading.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.PriorityBlockingQueue;
public class PriorityBlockingQueueTest {
PriorityBlockingQueue<String> priBlockQ = new PriorityBlockingQueue<String>();
public PriorityBlockingQueueTest(){
priBlockQ.add("300");
priBlockQ.add("400");
priBlockQ.add("100");
priBlockQ.add("500");
priBlockQ.add("200");
}
public void performTask() {
// traversing order not guaranteed
System.out.println("\nQueue iterator() : ");
Iterator<String> itr = priBlockQ.iterator();
while (itr.hasNext()) {
String string = (String) itr.next();
System.out.print(string+", ");
}
System.out.println("\n\nList iterator() : ");
List<String> list = new ArrayList<String>();
priBlockQ.drainTo(list);
itr = list.iterator();
while (itr.hasNext()) {
String string = (String) itr.next();
System.out.print(string+", ");
}
System.out.println("\n\ncontains() : "+priBlockQ.contains("400"));
System.out.println("\nremainingCapacity() : "+priBlockQ.remainingCapacity());
}
public static void main(String[] args) {
new PriorityBlockingQueueTest().performTask();
}
}
OUTPUT:
Queue iterator() :
100, 200, 300, 500, 400,
List iterator() :
100, 200, 300, 400, 500,
contains() : false
remainingCapacity() : 2147483647