Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

PriorityBlockingQueue — a concurrent priority queue

PriorityBlockingQueue is a thread-safe, logically unbounded priority queue. put inserts without waiting for space, while take removes the least available element and waits when the queue is empty.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<>();
PriorityBlockingQueue<E> ordered = new PriorityBlockingQueue<>(initialCapacity, comparator);
queue.put(element);
E next = queue.take(); // throws InterruptedException

PriorityBlockingQueue<E> in java.util.concurrent implements BlockingQueue<E>. Unlike PriorityQueue, it is thread-safe. Retrieval selects the least element under natural ordering or a Comparator supplied to the constructor, not the earliest inserted element. For numbers in natural order, smaller values are retrieved first.

PriorityBlockingQueue.put(E e) inserts an element without waiting for space: the queue is logically unbounded. The initialCapacity parameter specifies initial capacity, not an element limit. This does not provide backpressure; memory exhaustion can cause OutOfMemoryError.

PriorityBlockingQueue.take() retrieves and removes the head, waiting for an element if the queue is empty. It can throw InterruptedException, which must be handled or propagated. In contrast, poll() immediately returns null for an empty queue. Priority applies to currently available elements, not future submissions or the order in which consumers finish processing.

Elements cannot be null; incomparable elements can cause ClassCastException. Ties have no guaranteed FIFO ordering—use a secondary comparator key if that ordering is required. Iteration does not guarantee priority order. The example inserts every element before retrieval, making its output deterministic.

Examples

import java.util.concurrent.PriorityBlockingQueue;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(2);
        queue.put(30);
        queue.put(10);
        queue.put(20);

        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.poll());
    }
}

Result

10
20
30
null

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources