June 28, 2022

PriorityBlockingQueue in Java With Examples

PriorityBlockingQueue in Java is an implementation of BlockingQueue interface and is part of java.util.concurrent package.

PriorityBlockingQueue is an unbounded queue

PriorityBlockingQueue is logically unbounded, that's how it differs from ArrayBlockingQueue which is a bounded queue and LinkedBlockingQueue which is optionally-bounded.

PriorityBlockingQueue though unbounded is created with an initial capacity which you can specify or defaults to 11 if not specified. This initial capacity governs the size of an array used to store the elements on the queue.

Note that though the queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError).

Java PriorityBlockingQueue Constructors

  • PriorityBlockingQueue()- Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
  • PriorityBlockingQueue(int initialCapacity)- Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.
  • PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)- Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified Comparator.
  • PriorityBlockingQueue(Collection<? extends E> c)- Creates a PriorityBlockingQueue containing the elements in the specified collection.

PriorityBlockingQueue is thread-safe

PriorityBlockingQueue in Java is a thread safe variant of java.util.PriorityQueue class and supplies blocking retrieval operations. Insertion methods will never block as the queue is unbounded.

PriorityBlockingQueue does not allow null

PriorityBlockingQueue in Java does not allow null elements. It throws NullPointerException on attempts to add, put or offer a null.

public class PriorityBQ {
  public static void main(String[] args) {
    BlockingQueue bQueue = new PriorityBlockingQueue<>();	
    // putting null
    bQueue.add(null);
  }
}
Output
Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.concurrent.PriorityBlockingQueue.offer(PriorityBlockingQueue.java:480)
	at java.base/java.util.concurrent.PriorityBlockingQueue.add(PriorityBlockingQueue.java:464)
	at com.knpcode.programs.PriorityBQ.main(PriorityBQ.java:11)

PriorityBlockingQueue is an ordered Queue

Main feature of the PriorityBlockingQueue in Java is that the elements in this queue can be prioritized. The elements of the PriorityBlockingQueue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. By ordering the element as per your own comparison logic you can prioritize the elements in the priority queue. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).

The head of this queue is the least element with respect to the specified ordering. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

If multiple elements are having the equal priority, the head is one of those elements i.e. ties are broken arbitrarily. For example-

public class PriorityBQ {
  public static void main(String[] args) {
    BlockingQueue<Integer> bQueue = new PriorityBlockingQueue<>();    
    // adding elements
    bQueue.add(10);
    bQueue.add(5);
    bQueue.add(1);
    bQueue.add(3);
    // retrieving (element at head of the queue)        
    System.out.println("Element- " + bQueue.poll());
  }
}
Output
Element- 1

As you can see no Comparator is specified here so natural ordering for the Integers (ascending) is used to order the elements in PriorityBlockingQueue.

PriorityBlockingQueue with Comparator

Here is another Java example where a Comparator is specified for ordering the elements (descending order) in PriorityBlockingQueue.

public class PriorityBQ {
  public static void main(String[] args) {
    BlockingQueue<Integer> bQueue = new PriorityBlockingQueue<>(10, new MyComparator());    
    // adding elements
    bQueue.add(10);
    bQueue.add(5);
    bQueue.add(1);
    bQueue.add(3);
    // retrieving (head of the queue)        
    System.out.println("Element- " + bQueue.poll());
  }
}
//Comparator class
class MyComparator implements Comparator<Integer>{
  @Override
  public int compare(Integer o1, Integer o2) {
    return o2.compareTo(o1);
  }    
}
Output
Element- 10

Producer Consumer Implementation Using PriorityBlockingQueue in Java

BlockingQueue implementations are designed to be used primarily for producer-consumer queues so let's see an example of producer-consumer using PriorityBlockingQueue. In the example two threads are created one a producer thread and another a consumer thread.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityBQ {
  public static void main(String[] args) {
    BlockingQueue<String> bQueue = new PriorityBlockingQueue<>(10);    
    String[] Names = {"Krishna", "Madhusudan", "Muralidhar", "Jagannath"};
    // Producer 
    new Thread(()->{
      for(int i = 0; i < Names.length; i++){
        try {
          bQueue.put(Names[i]);
          System.out.println("Added to queue-" + Names[i]);                
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }).start();
        
    // Consumer
    new Thread(()->{
      for(int i = 0; i < Names.length; i++){
        try {
          System.out.println("Consumer retrieved- " + bQueue.take());					
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }).start();
  }
}
Output
Added to queue-Krishna
Added to queue-Madhusudan
Added to queue-Muralidhar
Added to queue-Jagannath
Consumer retrieved- Jagannath
Consumer retrieved- Krishna
Consumer retrieved- Madhusudan
Consumer retrieved- Muralidhar

That's all for the topic PriorityBlockingQueue in Java With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment