java - Is there an opposite for the DelayQueue? -
i need queue automatically remove elements older given amount of milliseconds - basically, want items in queue expire after time.
i see there delay queue seems doing opposite: 'an element can taken when delay has expired.' (i've never used it).
maybe there queue implementation need? better if bounded.
if want remove expired objects need delayqueue , thread extract expired objects it, this:
static class wrapper<e> implements delayed { e target; long exp = system.currenttimemillis() + 5000; // 5000 ms delay wrapper(e target) { this.target = target; } e get() { return target; } @override public int compareto(delayed o) { return 0; } @override public long getdelay(timeunit unit) { return unit.convert(exp - system.currenttimemillis(), timeunit.milliseconds); } } public static void main(string[] args) throws exception { final delayqueue<wrapper<integer>> q = new delayqueue<>(); q.add(new wrapper<>(1)); thread.sleep(3000); q.add(new wrapper<>(2)); new thread() { public void run() { try { for(;;) { wrapper<integer> w = q.take(); system.out.println(w.get()); } } catch (interruptedexception e) { throw new runtimeexception(e); } }; }.start(); }
Comments
Post a Comment