Close

Java Collections - DelayQueue.poll() 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

Methods:

public E poll()

Retrieves and removes the head of this queue, or returns null if this queue has no elements with an expired delay.



public E poll(long timeout,
              TimeUnit unit)
       throws InterruptedException

Retrieves and removes the head of this queue, waiting if necessary until an element with an expired delay is available on this queue, or the specified wait time expires.


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

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

int c = 0;
while (true) {
Task task = dq.poll();
if (task == null) {
continue;
}
c++;
System.out.println(task);
System.out.println("----");
if (c == 3) {
break;
}
}
}

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(100, 1000);
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=168, id=3}
----
Task{expectedDelay=574, id=1}
----
Task{expectedDelay=994, id=2}
----




See Also