PriorityBlockingQueue Class in Java (original) (raw)

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.

**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 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.