Video in progress

Strong Middle 🧺 Collections

How does DelayQueue work, and what do you watch out for when using it for delayed tasks?

DelayQueue is an unbounded BlockingQueue with a PriorityQueue inside: elements implement the Delayed interface, and take() returns only an element whose delay has expired. It is handy for retries, timeouts and TTL cleanup, but everything lives in memory and is lost on restart.

📖 Answer

record RetryTask(String id, long readyAtNanos) implements Delayed {
    public long getDelay(TimeUnit unit) {
        return unit.convert(readyAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
    }
    public int compareTo(Delayed o) {
        return Long.compare(getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS));
    }
}

DelayQueue<RetryTask> q = new DelayQueue<>();
q.put(new RetryTask("tx-1", System.nanoTime() + TimeUnit.SECONDS.toNanos(30)));
RetryTask t = q.take();   // returns after about 30 seconds

Inside there is one lock and a PriorityQueue: the element with the nearest deadline is at the head. Among the threads calling take(), one (the leader) sleeps until exactly that deadline, and the others wait for a signal, so there are no needless wakeups.

What to watch out for:

  • measure time with System.nanoTime(). currentTimeMillis jumps backward or forward when the clock is corrected (NTP), and tasks fire early or late;
  • compareTo must be consistent with getDelay, otherwise an expired element can get stuck in the middle of the queue;
  • size() also counts elements that haven't expired yet, while poll() returns null for them. "The queue isn't empty but nothing comes out" is a normal state;
  • there is no bound: if tasks pile up, you get an OOM.

In most cases ScheduledThreadPoolExecutor is more convenient: it uses a similar queue inside and also gives you cancellation (cancel) and thread management. If a task must survive a restart (a payment retry, for example), keep it in a DB or a broker. DelayQueue is only for in-memory work.