Close

Java Collections - DelayQueue.peek() Examples

Java Collections Java Java API 


Class:

java.util.concurrent.DelayQueue

java.lang.Objectjava.lang.Objectjava.util.AbstractCollectionjava.util.AbstractCollectionjava.util.CollectionCollectionjava.util.AbstractQueuejava.util.AbstractQueuejava.util.QueueQueuejava.util.concurrent.DelayQueuejava.util.concurrent.DelayQueuejava.util.concurrent.BlockingQueueBlockingQueueLogicBig

Method:

public E peek()

Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. Unlike poll , if no expired elements are available in the queue, this method returns the element that will expire next, if one exists.


Examples


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
----




See Also