In Java, the DelayQueue Class is the part of the java.util.concurrent package and implements the BlockingQueue interface. DelayQueue is a specialized implementation of a blocking queue that orders elements based on their delay time. Only elements whose delay has expired can be retrieved from the queue. If the delay has not expired, the consumer thread attempting to retrieve the element will be blocked until the delay expires.
- The queue orders elements based on their remaining delay, with the element that has the least remaining delay being the head of the queue.
- The consumer thread is blocked when trying to take elements from the queue until an element's delay has expired.
- The getDelay() method uses the TimeUnit enum(e.g. DAYS, HOURS, MINUTES, SECONDS) to specify the delay unit time.
Example: This example demonstrates how to use DelayQueue to store and execute tasks after a specified delay, processing elements as their delay times expire.
// Java Program to demonstrates the working of DelayQueue
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class Geeks {
// Class that implements the Delayed interface
static class MyDelayedElement implements Delayed {
private final String name;
private final long delayTime;
private final long startTime;
public MyDelayedElement(String name, long delayTime, TimeUnit unit) {
this.name = name;
// Convert delay to milliseconds
this.delayTime = unit.toMillis(delayTime);
this.startTime = System.currentTimeMillis();
}
@Override
public long getDelay(TimeUnit unit) {
long diff = startTime + delayTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return Long.compare(this.getDelay(TimeUnit.MILLISECONDS),
o.getDelay(TimeUnit.MILLISECONDS));
}
public String getName() {
return name;
}
}
public static void main(String[] args) throws InterruptedException {
// Create a DelayQueue
DelayQueue<MyDelayedElement> d = new DelayQueue<>();
// Add elements with different delay times
d.add(new MyDelayedElement("Task 1", 3, TimeUnit.SECONDS));
d.add(new MyDelayedElement("Task 2", 1, TimeUnit.SECONDS));
d.add(new MyDelayedElement("Task 3", 2, TimeUnit.SECONDS));
// Wait and process elements as their delays expire
while (!d.isEmpty()) {
// This will block until an
// element's delay has expired
MyDelayedElement t = d.take();
System.out.println("Executing: " + t.getName());
}
}
}
Output:
