Specialized Blocking Queues
Beyond the standard FIFO queues, java.util.concurrent provides two specialized queues for handling time-based and priority-based ordering.
DelayQueue #
DelayQueue is an unbounded blocking queue of Delayed elements, in which an element can only be taken when its delay has expired.
Canonical Usage: Use DelayQueue for internal caches with expiration, retry mechanisms, or any scenario where a task must wait a specific amount of time before being processed.
public class DelayedTask implements Delayed {
private final long executeTime;
public long getDelay(TimeUnit unit) {
return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
}
public int compareTo(Delayed other) {
return Long.compare(this.executeTime, ((DelayedTask)other).executeTime);
}
}
PriorityBlockingQueue #
PriorityBlockingQueue is an unbounded blocking queue that uses the same ordering rules as java.util.PriorityQueue but provides blocking retrieval operations.
Canonical Usage: Use PriorityBlockingQueue when you have tasks with different importance levels (e.g., “High Priority” vs “Low Priority”) and you want the consumer to always take the most important task available.
BlockingQueue<Task> pQueue = new PriorityBlockingQueue<>();
pQueue.put(new Task(Priority.LOW));
pQueue.put(new Task(Priority.HIGH));
Task t = pQueue.take(); // Returns the HIGH priority task first