Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
PriorityBlockingQueue Class in Java
Next article icon

PriorityBlockingQueue Class in Java

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The PriorityBlockingQueue class is part of the java.util.concurrent package and implements a thread-safe, priority-based blocking queue. It is similar to the PriorityQueue, but it supports operations for blocking threads, such as take() and put() which are not available in PriorityQueue.

  • Thread-safe and supports concurrent access
  • Elements are ordered by priority, not insertion order
  • Can block threads when the queue is empty or full
  • Allows custom prioritization via a comparator or natural ordering

Example: This example demonstrates adding elements to a PriorityBlockingQueue and printing the queue, which displays the elements in their internal order, not necessarily the order they were added.

Java
// Adding elements to priorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {     public static void main(String[] args) {                  // Create a PriorityBlockingQueue         PriorityBlockingQueue<Integer> q          = new PriorityBlockingQueue<>();          // Add elements to the q         q.add(10);         q.add(5);         q.add(20);         q.add(1);          System.out.println("PriorityBlockingQueue: " + q);     } } 

Output
PriorityBlockingQueue: [1, 5, 20, 10] 

PriorityBlockingQueue Hierarchy

The below diagram demonstrates the class and interface hierarchy of PriorityBlockingQueue, showing its relationships with Queue, BlockingQueue, AbstractQueue and AbstractCollection.

Hierarchy of PriorityBlockingQueue Class in Java

Declaration of PriorityBlockingQueue

In Java, the declaration of PriorityBlockingQueue can be done as:

PriorityBlockingQueue<Type> queue = new PriorityBlockingQueue<>();

Note: Here, "Type" represents the type of elements the queue will hold(e.g. Integer, String, or any custom object)

Constructors

Constructor

Description

PriorityBlockingQueue()

This constructor creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering. Adding element more than the initial capacity changes the capacity of the PriorityBlockingQueue dynamically as the PriorityBlockingQueue is not capacity constrained.


PriorityBlockingQueue(Collection<? extends E> c)

This constructor creates a PriorityBlockingQueue containing the elements in the specified collection.

 PriorityBlockingQueue(int initialCapacity)

This constructor creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to their natural ordering.

PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator)

This constructor creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.


Example 1: This example demonstrates the creation of a PriorityBlockingQueue and adds integers to it, printing the queue's contents.

Java
// Java program to demonstrate // PriorityBlockingQueue() constructor import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // create object of PriorityBlockingQueue         // using PriorityBlockingQueue() constructor         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>();          // add numbers         pbq.add(1);         pbq.add(2);         pbq.add(3);         pbq.add(4);         pbq.add(5);          System.out.println("PriorityBlockingQueue:" + pbq);     } } 

Output
PriorityBlockingQueue:[1, 2, 3, 4, 5] 


Example 2: This example demonstrates the creation of a PriorityBlockingQueue using a Collection vector to initialize the queue with elements.

Java
// Java program to demonstrate // PriorityBlockingQueue(Collection c) constructor import java.util.concurrent.PriorityBlockingQueue; import java.util.*;  public class Geeks {      public static void main(String[] args)     {         // Creating a Collection         Vector<Integer> v = new Vector<Integer>();         v.addElement(1);         v.addElement(2);         v.addElement(3);         v.addElement(4);         v.addElement(5);          // create object of PriorityBlockingQueue         // using PriorityBlockingQueue(Collection c)         // constructor         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>(v);          System.out.println("PriorityBlockingQueue:" + pbq);     } } 

Output
PriorityBlockingQueue:[1, 2, 3, 4, 5] 


Example 3: This example demonstrates the creation of a PriorityBlockingQueue with a specified initial capacity and adds elements to it.

Java
// Java program to demonstrate // PriorityBlockingQueue(int initialCapacity) // constructor import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // define capacity of PriorityBlockingQueue         int c = 15;          // create object of PriorityBlockingQueue         // using PriorityBlockingQueue(int initialCapacity)         // constructor         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>(c);          // add numbers         pbq.add(1);         pbq.add(2);         pbq.add(3);          // print queue         System.out.println("PriorityBlockingQueue:" + pbq);     } } 

Output
PriorityBlockingQueue:[1, 2, 3] 


Example 4: This example demonstrates the creation of a PriorityBlockingQueue with a specified initial capacity and a custom comparator(Comparator.reverseOrder()) to order elements in descending order.

Java
// Java program to demonstrate // PriorityBlockingQueue(int initialCapacity, Comparator // comparator) constructor import java.util.concurrent.PriorityBlockingQueue; import java.util.*;  public class Geeks {      public static void main(String[] args)     {         // define capacity of PriorityBlockingQueue         int c = 15;          // create object of PriorityBlockingQueue         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>(                 c, Comparator.reverseOrder());          // add numbers         pbq.add(1);         pbq.add(2);         pbq.add(3);          System.out.println("PriorityBlockingQueue:" + pbq);     } } 

Output
PriorityBlockingQueue:[3, 1, 2] 

Performing Various Operations on PriorityBlockingQueue

1. Adding Elements: We can use the add() method to insert elements to the PriorityBlockingQueue.

Example: This example demonstrates adding elements to a PriorityBlockingQueue with a specified initial capacity.

Java
// Java program to demonstrate adding elements // to the PriorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // define capacity of PriorityBlockingQueue         int c = 15;          // create object of PriorityBlockingQueue         PriorityBlockingQueue<Integer> pbq             = new PriorityBlockingQueue<Integer>(c);          // add numbers         pbq.add(1);         pbq.add(2);         pbq.add(3);          System.out.println("PriorityBlockingQueue:" + pbq);     } } 

Output
PriorityBlockingQueue:[1, 2, 3] 


2. Removing Elements: We can use the remove() method to remove the element from the queue. This method removes a single instance of the element passed as the parameter if it is present. 

Example: This example demonstrates adding, removing a specific element, and clearing all elements from a PriorityBlockingQueue.

Java
// Java program to demonstrate removing // elements from the PriorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {      public static void main(String[] args)     {         // define capacity of PriorityBlockingQueue         int c = 15;          // create object of PriorityBlockingQueue         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>(c);          // add numbers         pbq.add(1);         pbq.add(2);         pbq.add(3);          // print queue         System.out.println("PriorityBlockingQueue:" + pbq);          // remove element 2         pbq.remove(2);          // print queue         System.out.println("PriorityBlockingQueue:" + pbq);          // remove all the elements         pbq.clear();         System.out.println("PriorityBlockingQueue:" + pbq);      } } 

Output
PriorityBlockingQueue:[1, 2, 3] PriorityBlockingQueue:[1, 3] PriorityBlockingQueue:[] 


3. Accessing Elements: We can use peek() method to access the elements. It returns the element at the head of the PriorityBlockingQueue. If the PriorityBlockingQueue does not contain any element, then this method returns null.

Example: This example demonstrates adding elements to a PriorityBlockingQueue and accessing the head (highest priority element) using the peek() method.

Java
// Java Program Demonstrate accessing // elements of PriorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue;  public class Geeks {     public static void main(String[] args)     {         // define capacity of PriorityBlockingQueue         int c = 5;          // create object of PriorityBlockingQueue         PriorityBlockingQueue<Integer> Pbq                 = new PriorityBlockingQueue<Integer>(                 c);          // Add elements to PriorityBlockingQueue         Pbq.add(10);         Pbq.add(20);          // print PrioQueue         System.out.println("PriorityQueue: " + Pbq);          // get head of PriorityBlockingQueue         int h = Pbq.peek();          // print head of PriorityBlockingQueue         System.out.println("Head of Queue: " + h);     } } 

Output
PriorityQueue: [10, 20] Head of Queue: 10 


4. Iterating Elements: We can use the iterator() method to iterate over the element of PriorityBlockingQueue. The elements returned from this method do not follow any order.

Example: This example demonstrates iterating over the elements of a PriorityBlockingQueue using the iterator() method.

Java
// Java Program Demonstrate iterating // over PriorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue; import java.util.*;  public class Geeks{     public static void main(String[] args)     {          // define capacity of PriorityBlockingQueue         int c = 5;          // create object of PriorityBlockingQueue         PriorityBlockingQueue<String> pbq                 = new PriorityBlockingQueue<String>(                 c);          // Adding elements         pbq.add("Java");         pbq.add("C++");         pbq.add("Python");         pbq.add("Js");           // Call iterator() method of PriorityBlockingQueue         Iterator i = pbq.iterator();          // Print elements of iterator         // created from PriorityBlockingQueue         System.out.println("Elements in PriorityBlockingQueue are:");          while (i.hasNext()) {             System.out.print(i.next() + " ");         }     } } 

Output
Elements in PriorityBlockingQueue are: C++ Java Python Js 


5. Comparator Example: The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements

Example: This example demonstrates using a custom Comparator to order elements in a PriorityBlockingQueue and retrieving the comparator with the comparator() method.

Java
// Java Program Demonstrate comparator() // method and passing Comparator to PriorityBlockingQueue import java.util.concurrent.PriorityBlockingQueue; import java.util.*;  public class Geeks {     public static void main(String[] args)             throws InterruptedException     {          // create object of PriorityBlockingQueue         PriorityBlockingQueue<Integer> pbq                 = new PriorityBlockingQueue<Integer>(                 10, new Comparator<Integer>() {             public int compare(Integer a, Integer b)             {                 return a - b;             }         });          // Add numbers to PriorityBlockingQueue         pbq.put(45815616);         pbq.put(4981561);         pbq.put(4594591);         pbq.put(9459156);          // get String representation of         // PriorityBlockingQueue         String str = pbq.toString();          // Creating a comparator using comparator()         Comparator c = pbq.comparator();          // Displaying the comparator values         System.out.println("Comparator value: " + c);          if (c == null)             System.out.println(                     "PriorityBlockingQueue follows natural ordering");         else             System.out.println(                     "PriorityBlockingQueue follows : " + c);     } } 

Output
Comparator value: Geeks$1@1b28cdfa PriorityBlockingQueue follows : Geeks$1@1b28cdfa 

Methods

Methods

Description

add​(E e)Inserts the specified element into this priority queue.
clear()Atomically removes all of the elements from this queue.
comparator()Returns the comparator used to order the elements in this queue, or null if this queue uses the natural ordering of its elements.
contains​(Object o)Returns true if this queue contains the specified element.
drainTo​(Collection<? super E> c)Removes all available elements from this queue and adds them to the given collection.
drainTo​(Collection<? super E> c, int maxElements)Removes at most the given number of available elements from this queue and adds them to the given collection.
forEach​(Consumer<? super E> action)Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
iterator()Returns an iterator over the elements in this queue.
offer​(E e)Inserts the specified element into this priority queue.
offer​(E e, long timeout, TimeUnit unit)Inserts the specified element into this priority queue.
put​(E e)Inserts the specified element into this priority queue.
remainingCapacity()Always returns Integer.MAX_VALUE because a PriorityBlockingQueue is not capacity constrained.
remove​(Object o)Removes a single instance of the specified element from this queue, if it is present.
removeAll​(Collection<?> c)Removes all of this collection's elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate<? super E> filter)Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection<?> c)Retains only the elements in this collection that are contained in the specified collection (optional operation).
spliterator()Returns a Spliterator over the elements in this queue.
toArray()Returns an array containing all of the elements in this queue.
toArray​(T[] a)Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array.

Methods Declared in Class java.util.AbstractQueue

Method

Description

addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this queue.
element()Retrieves, but does not remove, the head of this queue.
remove()Retrieves and removes the head of this queue.

Methods Declared in Class java.util.AbstractCollection

Method

Description

containsAll​(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
isEmpty()Returns true if this collection contains no elements.
toString()Returns a string representation of this collection.

Methods Declared in Interface java.util.concurrent.BlockingQueue

Method

Description

poll​(long timeout, TimeUnit unit)Retrieves and removes the head of this queue, waiting up to the specified wait time if necessary for an element to become available.
take()Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Methods Declared in Interface java.util.Collection

Method

Description

addAll​(Collection<? extends E> c)Adds all of the elements in the specified collection to this collection (optional operation).
containsAll​(Collection<?> c)Returns true if this collection contains all of the elements in the specified collection.
equals​(Object o)Compares the specified object with this collection for equality.
hashCode()Returns the hash code value for this collection.
isEmpty()Returns true if this collection contains no elements.
parallelStream()Returns a possibly parallel Stream with this collection as its source.
size()Returns the number of elements in this collection.
stream()Returns a sequential Stream with this collection as its source.
toArray​(IntFunction<T[]> generator)Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.


Methods Declared in Interface java.util.Queue

Method

Description

element()Retrieves, but does not remove, the head of this queue.
peek()Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
poll()Retrieves and removes the head of this queue, or returns null if this queue is empty.
remove()Retrieves and removes the head of this queue.

Next Article
PriorityBlockingQueue Class in Java

C

code_r
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • Java-PriorityBlockingQueue
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    PriorityBlockingQueue clear() method in Java
    The clear() method of PriorityBlockingQueue removes all the elements from this queue. Therefore this method can be applied when it is required to clear the PriorityBlockingQueue. Syntax: public void clear() Parameter: This method takes no parameters. Returns: This method returns nothing. Exception:
    2 min read
    PriorityBlockingQueue add() Method in Java
    The add(E e) method of PriorityBlockingQueue inserts the element passed as a parameter to the method at the tail of this PriorityBlockingQueue. This method returns true if the adding of the element is successful. Else it returns false. Syntax: public boolean add(E e) Parameter: This method takes a m
    2 min read
    LinkedBlockingQueue Class in Java
    The LinkedBlockingQueue in Java is part of the java.util.concurrent package and implements the BlockingQueue interface. It provides a thread-safe, bounded, or unbounded queue used for managing tasks in a producer-consumer scenario. This queue can be used in multithreaded environments where one threa
    8 min read
    PriorityBlockingQueue contains() method in Java
    The contains(Object o) method checks whether PriorityBlockingQueue contains an object o or not. This method returns true, if and only if, this queue contains at least one element e which is equal to object o passed as parameter i.e. e.equals(o). If queue does not contains the Object o, then method r
    2 min read
    PriorityBlockingQueue comparator() method in Java
    The comparator() method of PriorityBlockingQueue returns the comparator that can be used to order the elements in a PriorityBlockingQueue. The method returns null value if the queue follows the natural ordering pattern of the elements. Syntax: public Comparator<? super E> comparator() Returns:
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences