
package com.logicbig.example.delayqueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class PeekExample {
public static void main(String... args) throws InterruptedException {
DelayQueue<Task> dq = new DelayQueue<>();
dq.offer(new Task(1));
dq.offer(new Task(2));
dq.offer(new Task(3));
for (int i = 0; i < 3; i++) {
Task task = dq.peek();
System.out.println(task);
System.out.println("remaining delay: " + task.getDelay(TimeUnit.MILLISECONDS));
System.out.println("----");
Thread.sleep(400);
}
}
private static class Task implements Delayed {
private final long end;
private final int expectedDelay;
private int id;
Task(int id) {
this.id = id;
expectedDelay = ThreadLocalRandom.current().nextInt(1000, 2000);
end = System.currentTimeMillis() + expectedDelay;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(end - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
return Long.compare(this.getDelay(TimeUnit.MILLISECONDS),
o.getDelay(TimeUnit.MILLISECONDS));
}
@Override
public String toString() {
return "Task{" +
"expectedDelay=" + expectedDelay +
", id=" + id +
'}';
}
}
}
Output
Task{expectedDelay=1315, id=3}
remaining delay: 1293
----
Task{expectedDelay=1315, id=3}
remaining delay: 885
----
Task{expectedDelay=1315, id=3}
remaining delay: 484
----