Video in progress
How does DelayQueue work, and when can you use it for delayed retries?
DelayQueue is a blocking queue whose elements implement the Delayed interface: an element comes out of take() only after its time is up. It's handy inside one JVM for things like "retry in 5 seconds", but everything is lost on a restart.
📖 Answer
Inside there's a PriorityQueue, with the element that expires soonest at the head. take() computes the time left on the head element and sleeps for exactly that long, with no busy-waiting.
record RetryTask(String paymentId, int attempt, long readyAtNanos) implements Delayed {
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(readyAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
}
@Override
public int compareTo(Delayed o) {
return Long.compare(getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS));
}
}
DelayQueue<RetryTask> retries = new DelayQueue<>();
retries.put(new RetryTask("p-42", 1, System.nanoTime() + TimeUnit.SECONDS.toNanos(5)));
// worker thread
RetryTask t = retries.take(); // waits until 5 seconds have passed
What to know:
- the queue is unbounded and
putnever blocks, so put a limit on the number of retries yourself; size()also counts elements whose time hasn't come yet;- use
System.nanoTime()for time, notcurrentTimeMillis: if the clock is adjusted, the delays break.
The alternative is ScheduledExecutorService.schedule(task, 5, SECONDS). It also uses a delay queue internally and is often simpler. DelayQueue is useful when you want control over the elements yourself: looking into the queue, cancelling, taking them in groups (drainTo).
But for important work, like resending a payment, an in-memory queue is not enough: if the pod restarts, all the waiting retries are gone. There you need a table in the DB with a next_attempt_at column, or the broker's delayed messages.
Sign up to mark studied questions and save your progress.