Close

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


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

public static void main(String... args) throws InterruptedException {
DelayQueue<Task> queue = new DelayQueue<>();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
Task t = new Task(i);
System.out.println("putting new Task: " + t + ", thread: " +
Thread.currentThread().getName());
queue.put(t);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.err.println(e);
}
}
}
}).start();

for (int i = 0; i < 3; i++) {
System.out.println("taking next Task, thread: " + Thread.currentThread().getName());
long l = System.currentTimeMillis();
Task task = queue.take();
System.out.println("taken: " + task);
System.out.println("blocked for millis: " + (System.currentTimeMillis() - l));
}
}

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

taking next Task, thread: com.logicbig.example.delayqueue.TakeExample.main()
putting new Task: Task{expectedDelay=851, id=1}, thread: Thread-0
putting new Task: Task{expectedDelay=638, id=2}, thread: Thread-0
taken: Task{expectedDelay=851, id=1}
blocked for millis: 850
taking next Task, thread: com.logicbig.example.delayqueue.TakeExample.main()
putting new Task: Task{expectedDelay=720, id=3}, thread: Thread-0
taken: Task{expectedDelay=638, id=2}
blocked for millis: 300
taking next Task, thread: com.logicbig.example.delayqueue.TakeExample.main()
taken: Task{expectedDelay=720, id=3}
blocked for millis: 582




See Also