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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.