Multithreading: PriorityBlockingQueue drains in priority order

A PriorityBlockingQueue is an unbounded blocking queue backed by a heap, so poll() always returns the smallest remaining element by natural ordering rather than the one inserted first. Insertion order is not preserved at all once elements are mixed in.

Code
PriorityBlockingQueue<Integer> pq = new PriorityBlockingQueue<>();
pq.offer(5);
pq.offer(1);
pq.offer(3);
List<Integer> drained = new ArrayList<>();
while (!pq.isEmpty()) drained.add(pq.poll());
System.out.println("Drained in priority order: " + drained);
Output
Drained in priority order: [1, 3, 5]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms