PriorityBlockingQueue Ordered Drain

Drain a PriorityBlockingQueue by priority: elements with the highest comparator order come out first, and take blocks while the queue is empty.

JavaResilience

Code

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

public class PrintQueue {

    record Job(String name, int priority) {}

    public static void main(String[] args) throws InterruptedException {
        // 优先级数值越大越先出队(comparator 决定堆序)
        PriorityBlockingQueue<Job> queue = new PriorityBlockingQueue<>(
                11, Comparator.comparingInt(Job::priority).reversed());

        queue.put(new Job("nightly-report", 1));
        queue.put(new Job("checkout-retry", 9));
        queue.put(new Job("cache-warm", 4));

        // take 在空队列上阻塞等待;这里元素足够,直接按序取完
        while (!queue.isEmpty()) {
            System.out.println("run: " + queue.take().name());
        }
    }
}

How it works

PriorityBlockingQueue Ordered Drain reduces to the classes PrintQueue and Job.

Repetition is confined to while (!queue.isEmpty()) — the rest of the file is straight-line.

Using it

Running the file prints labeled results such as run: — each operation’s effect is visible in the output.

Key statements

queue.put(new Job("nightly-report", 1));
queue.put(new Job("checkout-retry", 9));
queue.put(new Job("cache-warm", 4));

Interactive Tools for This Topic

FAQ

What does PriorityBlockingQueue Ordered Drain print when run?
Running the file directly is enough — expect labeled output lines such as `run:`.