DelayQueue With Delayed Retry Tasks

Schedule retries with a DelayQueue: Delayed tasks become takeable only after their delay elapses, and the earliest deadline always leaves the queue first.

JavaResilience

Code

snippet
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class RetryScheduler {

    // 元素实现 Delayed:getDelay 为正表示还没到期
    record RetryTask(String name, long dueAtNanos) implements Delayed {
        @Override public long getDelay(TimeUnit unit) {
            return unit.convert(dueAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
        }
        @Override public int compareTo(Delayed other) {
            return Long.compare(getDelay(TimeUnit.NANOSECONDS),
                    other.getDelay(TimeUnit.NANOSECONDS));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<RetryTask> queue = new DelayQueue<>();
        queue.put(new RetryTask("fast", System.nanoTime() + 50_000_000));
        queue.put(new RetryTask("slow", System.nanoTime() + 200_000_000));

        // take() 阻塞到队头元素到期;到期早的先出队
        while (!queue.isEmpty()) {
            RetryTask task = queue.take();
            System.out.println("expired: " + task.name());
        }
    }
}

How it works

Count the classes RetryScheduler and RetryTask and the functions getDelay and compareTo as the entire surface area of DelayQueue With Delayed Retry Tasks.

The file repeats itself only inside while (!queue.isEmpty()).

Using it

The main signature reads public long getDelay(TimeUnit unit)

The demo output is labeled (expired:), so every printed line maps back to its originating operation.

Key statements

return unit.convert(dueAtNanos - System.nanoTime(), TimeUnit.NANOSECONDS);
return Long.compare(getDelay(TimeUnit.NANOSECONDS),
other.getDelay(TimeUnit.NANOSECONDS));

Interactive Tools for This Topic

FAQ

What does DelayQueue With Delayed Retry Tasks print when run?
Invoke the file as-is — the `expired:` prefixes identify which step printed each line.