← 中文资源

简体中文版本

DelayQueue 延迟重试队列

DelayQueue 里的元素实现 Delayed 接口:延迟未到 take() 会一直阻塞,到期早的先出队,天然适合做重试与超时调度。

阅读英文原文

实现说明

真正干活的是类 RetryScheduler、RetryTask和函数 getDelay、compareTo,其余都是接线。 本示例的循环部分是 while (!queue.isEmpty())。

使用要点

  • 跑完文件,输出里会留下标记——expired:。

常见问题

运行「DelayQueue 延迟重试队列」会打印什么?

运行文件本身,expired: 这些前缀各对应一段演示逻辑。

主签名形如 public long getDelay(TimeUnit unit)

核心语句

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

代码示例

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());
        }
    }
}