Im trying to test out using a DelayQueue but the poll method dosen't seem to be working properly. The docs say...
The specified wait time is one second and the elements are delayed a lot longer than that.E poll(long timeout, TimeUnit unit)
Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time if no elements with an unexpired delay are present on this queue.![]()
Code:import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; import java.util.concurrent.DelayQueue; public class DelayTest{ public static void main(String[] args){ DelayQueue<DelayedElement> dq = new DelayQueue<DelayedElement>(); dq.put(new DelayedElement(32,"32")); dq.put(new DelayedElement(25,"25")); dq.put(new DelayedElement(15,"15")); try{ DelayedElement de = dq.poll(1, TimeUnit.SECONDS); System.out.println(de.getDelayTime()); }catch(InterruptedException ie){ System.err.println(ie); } } } class DelayedElement implements Delayed, Comparable<Delayed>{ private long sec; private String delay; public long getDelay(TimeUnit unit){ long d = unit.convert(sec - (System.currentTimeMillis() / 1000), TimeUnit.SECONDS); return d; } public DelayedElement(long sec, String delay){ this.sec = sec; this.delay = delay; } public String getDelayTime(){ return delay; } public int compareTo(Delayed other){ if(other == this) return 0; DelayedElement x = (DelayedElement)other; long diff = sec - x.sec; if(diff < 0) return -1; else if(diff > 0) return 1; else return 1; } }




Reply With Quote