Dubbo3时间轮

7.2.8 HashedWheelTimer图解

✅ 1. 架构图

在这里插入图片描述

✅ 2. 初始化流程图

在这里插入图片描述

✅ 3. 添加定时任务流程图

在这里插入图片描述

✅ 4. Worker 线程处理流程图

在这里插入图片描述

✅ 5. 任务转移流程图

在这里插入图片描述

✅ 6. 任务到期处理流程

在这里插入图片描述

✅ 7. 时间轮工作时序图
Application HashedWheelTimer Worker Thread HashedWheelBucket newTimeout(task, delay, unit) 创建 HashedWheelTimeout 加入 timeouts 队列 返回 Timeout start() 启动 Worker 线程 waitForNextTick() processCancelledTasks() 处理 cancelledTimeouts 队列 transferTimeoutsToBuckets() 从 timeouts 队列取出任务 根据 deadline 计算并添加到对应桶 expireTimeouts() 遍历桶内任务 处理到期任务 (remainingRounds<=0) 执行 TimerTask.run() 更新未到期任务 (remainingRounds--) loop [每个 tick 周期] Application HashedWheelTimer Worker Thread HashedWheelBucket
✅ 8. 任务取消时序图
Application HashedWheelTimer HashedWheelTimeout Worker Thread timeout.cancel() CAS 设置状态为 ST_CANCELLED 加入 cancelledTimeouts 队列 返回 true processCancelledTasks() 从 cancelledTimeouts 取出任务 timeout.remove() 从桶中移除自己 减少 pendingTimeouts 计数 Application HashedWheelTimer HashedWheelTimeout Worker Thread

这些图表展示了 HashedWheelTimer 的核心工作机制,包括初始化过程、任务添加、任务处理以及任务取消等关键环节。整体设计采用了生产者-消费者模式,通过队列解耦了任务提交和任务处理的过程,并利用时间轮算法优化了大量定时任务的管理效率。

7.2.9 举例说明

  1. 用户提交一个延迟为 T = 300 秒(5 分钟) 的任务;
  2. 计算总 tick 数:totalTicks = T / tickDuration = 300_000ms / 100ms = 3000 ticks. (时间轮的指针,是一个步长为 1 的单调递增计数器)
  3. 由于 wheel 只有 512 个槽,计算:
    • remainingRounds = totalTicks / ticksPerWheel = 3000 / 512 ≈ 5 轮
      • remainingRounds ,剩余的轮数
    • stopIndex = (currentTick + totalTicks) % ticksPerWheel
      • 某个槽位停止下来
  4. 将任务封装为 HashedWheelTimeout,记录ticksPerWheel
  5. 时间轮工作线程每 tick 一次:
    • 当指针到达 stopIndex 时,检查该槽位所有任务;
    • 若 remainingRounds > 0,则 remainingRounds--不执行任务,继续等待下一轮;
    • 直到 remainingRounds == 0,才真正执行任务。

✅ 这就是 “多轮计数”机制,无需多级时间轮,也能支持任意长时间任务。

🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉

  • Enjoy it

🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐