0
Sponsored Links


Ad by Google
In this tutorial, we will see What is PriorityBlockingQueue? How to use PriorityBlockingQueue and Example of PriorityBlockingQueue. But before that, I request you to read what is BlockingQueue in java

What is PriorityBlockingQueue

The PriorityBlockingQueue is an implementation of BlockingQueue interface, which extends Queue and Queue extends Collection interface. That means PriorityBlockingQueue act as Queue(FIFO) and supports all the operations of Collection interface.
The PriorityBlockingQueue is an un-bounded Queue and act as PriorityQueue. It act as a PriorityQueue, so the priority ordering rule remained same as java.util.PriorityQueue class. PriorityBlockingQueue is an implementation of BlockingQueue, means it does not allow null element.
The PriorityBlockingQueue is un-bounded queue unlike ArrayBlockingQueue, that means you can add as much as element you want to but, but once memory get exhausted it will throws OutOfMemoryError. The priority of the queue is based on natural order. The requirement is insert only those object as an element in PriorityBlockingQueue which implement Comparable interface otherwise it will throws ClassCastException.
If you are planing to iterate priority queue using iterator(), It's not guaranteed the traversing order of the element. But to traverse the element in ordered you can sort the elements using Arrays.sort(pq.toArray()) method.

PriorityBlockingQueue Example

Of course PriorityBlockingQueue, is thread safe and designed to be used primarily for producer-consumer queues.
OK, Let's see an example of PriorityBlockingQueue.
Product.java implements Comparable interface, you can read more about Comparable Vs Comparator interface.
package com.javamakeuse.poc;

public class Product implements Comparable<Product> {

 private String productName;

 public Product(String productName) {
  super();
  this.productName = productName;
 }
 public String getProductName() {
  return productName;
 }
 @Override
 public String toString() {
  return "Product [productName=" + productName + "]";
 }
 @Override
 public int compareTo(Product o) {
  return productName.compareTo(o.getProductName());
 }
}
PriorityBlockingQueueExample.java testing PriorityBlockingQueue implementation
package com.javamakeuse.poc;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class PriorityBlockingQueueExample {

 public static void main(String[] args) {
  BlockingQueue<Product> priorityBlockingQueue = new PriorityBlockingQueue<>();
  priorityBlockingQueue.add(new Product("xyz"));
  priorityBlockingQueue.add(new Product("abc"));
  try {
   System.out.println(priorityBlockingQueue.take());
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}

OUT PUT
Product [productName=abc]
Sponsored Links

0 comments:

Post a Comment