简介
定时器是一种在实际的应用中非常常见和有效的一种工具,其原理就是把要执行的任务按照执行时间的顺序进行排序,然后在特定的时间进行执行。JAVA提供了java.util.Timer和java.util.concurrent.ScheduledThreadPoolExecutor等多种Timer工具,但是这些工具在执行效率上面还是有些缺陷,于是netty提供了HashedWheelTimer,一个优化的Timer类。
一起来看看netty的Timer有何不同吧。
java.util.Timer
Timer是JAVA在1.3中引入的。所有的任务都存储在它里面的TaskQueue中:
private final TaskQueue queue = new TaskQueue();
TaskQueue的底层是一个TimerTask的数组,用于存储要执行的任务。
private TimerTask[] queue = new TimerTask[128];
看起来TimerTask只是一个数组,但是Timer将这个queue做成了一个平衡二叉堆。
当添加一个TimerTask的时候,会插入到Queue的最后面,然后调用fixup方法进行再平衡:
void add(TimerTask task) {
// Grow backing store if necessary
if (size + 1 == queue.length)
queue = Arrays.copyOf(queue, 2*queue.length);
queue[++size] = task;
fixUp(size);
}
当从heap中移出运行的任务时候,会调用fixDown方法进行再平衡:
void removeMin() {
queue[1] = queue[size];
queue[size--] = null; // Drop extra r

本文介绍了Netty的HashedWheelTimer,对比了java.util.Timer和java.util.concurrent.ScheduledThreadPoolExecutor,分析了HashedWheelTimer基于Simple Timing Wheel算法的优化,实现了接近O(1)的效率,提供了一种更高效的定时任务解决方案。
最低0.47元/天 解锁文章
1715

被折叠的 条评论
为什么被折叠?



