java timer缺陷

来源:互联网 发布:柯尔特蟒蛇357淘宝模型 编辑:程序博客网 时间:2024/06/01 22:50

1.Timer管理时间延迟缺陷
Timer执行周期任务时依赖系统时间,如果当前系统时间发生变化会出现一些执行上的变化ScheduledExecutorService基于时间的延迟,不会由于系统时间的改变发生执行变化。

2.Timer抛出异常缺陷
timer中的任务如果有一个抛出异常, 则后边的任务不会执行。
这个缺陷可以从Timer.java中的mainLoop方法看出,
整个方法只抛出了InterruptedException,如果是其他的异常,那么就爽了!

/**     * 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();                    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) {            }        }    }}
阅读全文
0 0
原创粉丝点击