JDK Timer实现详解

概述

定时器是工程开发中比较常用的工具,本文研究JDK中Timer定时器的实现原理。在JDK中,Timer主要由TimerTask,TimerThread,TaskQueue组成。

TimerTask

TimerTask主要用来定义定时时间到来时,需要干什么事情,TimerTask继承自Runnable,所以具体的任务定义在run接口中。Task的状态有如下几种:

    /**
     * This task has not yet been scheduled.
     */
    static final int VIRGIN = 0;

    /**
     * This task is scheduled for execution.  If it is a non-repeating task,
     * it has not yet been executed.
     */
    static final int SCHEDULED   = 1;

    /**
     * This non-repeating task has already executed (or is currently
     * executing) and has not been cancelled.
     */
    static final int EXECUTED    = 2;

    /**
     * This task has been cancelled (with a call to TimerTask.cancel).
     */
    static final int CANCELLED   = 3;

VIRGIN表示Task刚刚被创建,SCHEDULED表示Task已经被加入TaskQueue中,等待调度,EXECUTED表示Task已经被执行,CANCELLED表示Task已经被取消。

TaskQueue

顾名思义,TaskQueue就是用来保存TimerTask的队列,当有新的Task add进来时,会保存到改队列中。需要注意的是,TaskQueue的内部实现使用的是最小堆,堆顶的Task是最近即将到时间的Task,所以在调度任务时,每次只需要取出堆顶元素,判断时间是否已到即可,效率非常高。下面是TaskQueue的核心代码,其实就是最小堆的实现代码:

    /**
     * Adds a new task to the priority queue.
     */
    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);
    }
    /**
     * Establishes the heap invariant (described above) assuming the heap
     * satisfies the invariant except possibly for the leaf-node indexed by k
     * (which may have a nextExecutionTime less than its parent's).
     *
     * This method functions by "promoting" queue[k] up the hierarchy
     * (by swapping it with its parent) repeatedly until queue[k]'s
     * nextExecutionTime is greater than or equal to that of its parent.
     */
    private void fixUp(int k) {
        while (k > 1) {
            int j = k >> 1;
            if (queue[j].nextExecutionTime <= queue[k].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

    /**
     * Establishes the heap invariant (described above) in the subtree
     * rooted at k, which is assumed to satisfy the heap invariant except
     * possibly for node k itself (which may have a nextExecutionTime greater
     * than its children's).
     *
     * This method functions by "demoting" queue[k] down the hierarchy
     * (by swapping it with its smaller child) repeatedly until queue[k]'s
     * nextExecutionTime is less than or equal to those of its children.
     */
    private void fixDown(int k) {
        int j;
        while ((j = k << 1) <= size && j > 0) {
            if (j < size &&
                queue[j].nextExecutionTime > queue[j+1].nextExecutionTime)
                j++; // j indexes smallest kid
            if (queue[k].nextExecutionTime <= queue[j].nextExecutionTime)
                break;
            TimerTask tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
            k = j;
        }
    }

    /**
     * Establishes the heap invariant (described above) in the entire tree,
     * assuming nothing about the order of the elements prior to the call.
     */
    void heapify() {
        for (int i = size/2; i >= 1; i--)
            fixDown(i);
    }

TimerThread

同样地,顾名思义,TimerThread就是用来调度TaskQueue中的任务的线程。TimerThread的核心逻辑如下:

private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
                    if (queue.isEmpty())
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn't yet fired; wait
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();
            } catch(InterruptedException e) {
            }
        }
    }

总结一下:TimerThread会起一个while循环,每一次循环判断当前TaskQueue队列是否为空,如果队列为空,并且可能会有新的Task会被调度,则等待新的Task到来,如果wait被唤醒之后队列还是为空,则表示此次wait是被Timer的cancel动作唤醒的,Timer的cancel动作如下:

    public void cancel() {
        synchronized(queue) {
            thread.newTasksMayBeScheduled = false;
            queue.clear();
            queue.notify();  // In case queue was already empty.
        }
    }

将newTasksMayBeScheduled设置为false的同时,调用queue的notify方法,唤醒正在等待queue的线程。需要注意的是,唤醒queue的方式还有另外一种,稍后介绍。

否则,如果queue不为空,则从queue中取出当前最近即将到时间的Task,然后判断Task的执行时间是否已经到了,如果还没到,则计算目标调度时间和当前时间的差值delta,继续wait delta毫秒,wait时间到之后会结束本次循环,在下一次循环中,如果没有新的更早的task加入,则当前的task将会被执行。

核心部分

从上面的介绍可知,TimerThread的调度核心是起一个while循环,不断检查是否有task需要执行,其中两次调用了queue.wait()方法。那在哪些情况下queue.notify()方法会被调用呢?

  1. 当向Timer中增加新的Task,并且该Task是所有Task中应该被最先执行的Task时:

      private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");
    
        // Constrain value of period sufficiently to prevent numeric
        // overflow while still being effectively infinitely large.
        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;
    
        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");
    
            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }
    
            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();
        }
    }

    为什么需要queue.getMin() == task时才调用notify方法呢?因为只有新加入的task是所有Task中要被最早执行的task时,才会需要打断TimeThread的等待状态。举个例子,当前队列中有两个task,分别是A(3分钟后到时间)、B(5分钟后到时间),此时TimerThread正在等待A的时间到来,所以会调用queue.wait(3min),这个时候,队列中新增一个任务C(1分钟后到时),如果不打断queue.wait(3min),那当wait(3min)自然结束时,C任务已经过期了… 但是如果新加入的C任务是需要在4分钟后执行,那就没必要打断wait(3min)的状态,因为就算wait(3min)自然结束时,C也还没到时间.

  2. 调用Timer的cancel接口时

        public void cancel() {
        synchronized(queue) {
            thread.newTasksMayBeScheduled = false;
            queue.clear();
            queue.notify();  // In case queue was already empty.
        }
    }

    该方法会把队列清空,并且把newTasksMayBeScheduled标志设置为false,这个时候如果不调用queue.notify(),在queue本来就已经empty的情况下,TimerThread的mainloop就会陷入死等待:

     /**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
  3. 是否上面两种情况调用notify就已经足够了?当queue为空,并且没人调用add或cancel方法时,TimerThread永远都不会stop,所以机智的JDK还加上了一种比较保险的方法:

        /**
     * This object causes the timer's task execution thread to exit
     * gracefully when there are no live references to the Timer object and no
     * tasks in the timer queue.  It is used in preference to a finalizer on
     * Timer as such a finalizer would be susceptible to a subclass's
     * finalizer forgetting to call it.
     */
    private final Object threadReaper = new Object() {
        protected void finalize() throws Throwable {
            synchronized(queue) {
                thread.newTasksMayBeScheduled = false;
                queue.notify(); // In case queue is empty.
            }
        }
    };

    用到了Object对象的finalize方法,大家都知道finalize方法是对象被GC的时候调用的。上述做法的思路是:当一个Timer已经没有任何对象引用时,自然不会有新的Task加入到队列中,Timer对象自然也就会被垃圾回收,此时TimerThread也就应该stop了,所以在垃圾回收的时候还应该把newTasksMayBeScheduled设置为false,并且唤起正在wait的TimerThread线程。所以说,如果你创建的Timer不再需要了,最好是调用cancel接口手动取消,否则的话TimerThread就需要等到垃圾回收的时候才会stop。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值