Inserts the specified element into this delay queue.
Inserts the specified element into this delay queue. As the queue is unbounded this method will never block.
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 OfferExample {
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));
//sleep some times so that some task will be ready for poll
Thread.sleep(300);
for (int i = 0; i < 3; i++) {
long l = System.currentTimeMillis();
Task task = dq.poll();
System.out.println(task);
System.out.println("blocked for millis: " + (System.currentTimeMillis() - l));
System.out.println("----");
}
}
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
null
blocked for millis: 0
----
null
blocked for millis: 0
----
null
blocked for millis: 0
----