一个Hash Wheel Timer是一个环形结构,可以想象成时钟,分为很多格子,一个格子代表一段时间(越短Timer精度越高),并用一个List保存在该格子上到期的所有任务,同时一个指针随着时间流逝一格一格转动,并执行对应List中所有到期的任务。任务通过取模(实际是通过位运算)决定应该放入哪个格子。
假设一个格子是1秒,则整个wheel能表示的时间段为8s,假如当前指针指向2,此时需要调度一个3s后执行的任务,显然应该加入到(2+3=5)的方格中,指针再走3次就可以执行了;如果任务要在10s后执行,应该等指针走完一个round零2格再执行,因此应放入4,同时将round(1)保存到任务中。检查到期任务时应当只执行round为0的,格子上其他任务的round应减1。
schedule: O(1)
cancel : O(1)
expire : 最坏情况O(n),平均O(1) // 显然格子越多每个格子对应的List就越短,越接近O(1);最坏情况下所有的任务都在一个格子中,O(n)。
时间轮在 Netty(4.x)中的实现方式:
重要属性
//内部负责添加任务, 累加tick, 执行任务等.
private final Worker worker = new Worker();
//负责创建Worker线程.
private final Thread workerThread;
//时间刻度之间的时长(默认100ms), 通俗的说, 就是多久tick++一次.
//每 tick 一次的时间间隔, 每 tick 一次就会到达下一个槽位
private final long tickDuration;
//轮中的 slot 数
int ticksPerWheel;
//wheel数组元素, 负责存放HashedWheelTimeout链表.
private final HashedWheelBucket[] wheel;
构造方法
//轮(Round) :一轮的时长为 tickDuration * ticksPerWheel, 也就是转一圈的时长.
public HashedWheelTimer(
ThreadFactory threadFactory,
long tickDuration, TimeUnit unit, int ticksPerWheel, boolean leakDetection,
long maxPendingTimeouts) {
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
}
if (unit == null) {
throw new NullPointerException("unit");
}
if (tickDuration <= 0) {
throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
}
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
// Normalize ticksPerWheel to power of two and initialize the wheel.
////创建wheel数组, 和HashMap的entry数组长度类似, 为2的幂
wheel = createWheel(ticksPerWheel);
//用于计算任务存放wheel的索引
//因为wheel长度为2的次方, 则, 如果长度为16(10000), mask就为15(1111)
//那么, 通过 n & mask 就可以实现 类似于 n % mask, 而 & 更高效........
mask = wheel.length - 1;
// Convert tickDuration to nanos.
////tickDuration 不能大于 Long.MAX_VALUE / wheel.length, 也就是一轮的时间不能大于Long.MAX_VALUE 纳秒
long duration = unit.toNanos(tickDuration);
// Prevent overflow.
// 校验是否存在溢出。
// 即指针转动的时间间隔不能太长。
// 太长导致tickDuration*wheel.length>Long.MAX_VALUE没法计算了
if (duration >= Long.MAX_VALUE / wheel.length) {
throw new IllegalArgumentException(String.format(
"tickDuration: %d (expected: 0 < tickDuration in nanos < %d",
tickDuration, Long.MAX_VALUE / wheel.length));
}
if (duration < MILLISECOND_NANOS) {
if (logger.isWarnEnabled()) {
logger.warn("Configured tickDuration %d smaller then %d, using 1ms.",
tickDuration, MILLISECOND_NANOS);
}
this.tickDuration = MILLISECOND_NANOS;
} else {
this.tickDuration = duration;
}
//创建worker线程
workerThread = threadFactory.newThread(worker);
// 这里默认是启动内存泄露检测:当HashedWheelTimer实例超过当前cpu可用核数*4的时候,将发出警告
leak = leakDetection || !workerThread.isDaemon() ? leakDetector.track(this) : null;
//最长的执行任务的时间
this.maxPendingTimeouts = maxPendingTimeouts;
//检测时间轮是否太多
if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT &&
WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) {
reportTooManyInstances();
}
}
看看启动的时候都做了些什么:
////启动Timer, 不需要显示调用, 调用 newTimeout 时, 会自动调用该方法
public void start() {
//初始为WORKER_STATE_INIT, cas修改为WORKER_STATE_STARTED, 并启动worker线程
//状态流转
//如果初始化过了,就启动worker
//如果已经开始就跳过。如果关闭了会报错
switch (WORKER_STATE_UPDATER.get(this)) {
case WORKER_STATE_INIT:
if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) {
workerThread.start