Java PriorityBlockingQueue

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.

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 Remove Operation Examine Operation

PriorityBlockingQueue Example

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

public class PriorityBlockingQueueExample {

	public static void main(String[] args) throws InterruptedException {

		BlockingQueue<Student> priorityBlockingQueue=new PriorityBlockingQueue<Student>(4,new Student());
		priorityBlockingQueue.put(new Student(4));
		priorityBlockingQueue.put(new Student(2));
		priorityBlockingQueue.put(new Student(3));
		priorityBlockingQueue.put(new Student(1));

class Student implements Comparator<Student>
	Integer id;

	public Student(Integer id)
	public Student()
	public int compare(Student s1,Student s2) {
Student Id :1
Student Id :2
Student Id :3
Student Id :4