Java Review - 使用Timer时需要注意的事情

简介: Java Review - 使用Timer时需要注意的事情

195d03d17afc4a928bc581f313b01dfe.png


概述


先说结论 当一个Timer运行多个TimerTask时,只要其中一个TimerTask在执行中向run方法外抛出了异常,则其他任务也会自动终止

我们看插件的提示


6214968e11434f3dbe1d71ac239e6858.png


问题复现


import java.util.Timer;
import java.util.TimerTask;
/**
 * @author 小工匠
 * @version 1.0
 * @description: TODO
 * @date 2021/11/21 20:28
 * @mark: show me the code , change the world
 */
public class TimerTest {
    // 定时器
    static Timer timer = new Timer();
    public static void main(String[] args) {
        // 任务1 , 延迟500ms执行  1秒执行一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task1 Running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 模拟发生异常
                throw new RuntimeException();
            }
        },500,1000);
        // 任务2, 延迟1000ms执行  1秒执行一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("Task2 Running");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },1000,1000);
    }
}

如上代码首先添加了第一个任务,让其在500ms后执行。然后添加了第二个任务在1s后执行,我们期望当第一个任务输出Task1 Running后,等待1s,第二个任务输出Task1 Running,,然后循环,每隔1秒执行一次。

但是执行代码后,输出结果为


968563a051224a2d994cd778c2c290de.png


源码分析

Timer的原理模型如下

7028797b315340a3a3920b56cd2c2f27.png


TaskQueue是一个由平衡二叉树堆实现的优先级队列,每个Timer对象内部有一个TaskQueue队列。用户线程调用Timer的schedule方法就是把TimerTask任务添加到TaskQueue队列。在调用schedule方法时,long delay参数用来指明该任务延迟多少时间执行。


·TimerThread是具体执行任务的线程,它从TaskQueue队列里面获取优先级最高的任务进行执行。需要注意的是,只有执行完了当前的任务才会从队列里获取下一个任务,而不管队列里是否有任务已经到了设置的delay时间。一个Timer只有一个TimerThread线程,所以可知Timer的内部实现是一个多生产者-单消费者模型。


源码分析



05800d41f11049aca69ec503103341ec.png


从该实现模型我们知道,要探究上面的问题只需研究TimerThread的实现就可以了。TimerThread的run方法的主要逻辑代码如下。

/**
 * This "helper class" implements the timer's task execution thread, which
 * waits for tasks on the timer queue, executions them when they fire,
 * reschedules repeating tasks, and removes cancelled tasks and spent
 * non-repeating tasks from the queue.
 */
class TimerThread extends Thread {
    /**
     * This flag is set to false by the reaper to inform us that there
     * are no more live references to our Timer object.  Once this flag
     * is true and there are no more tasks in our queue, there is no
     * work left for us to do, so we terminate gracefully.  Note that
     * this field is protected by queue's monitor!
     */
    boolean newTasksMayBeScheduled = true;
    /**
     * Our Timer's queue.  We store this reference in preference to
     * a reference to the Timer so the reference graph remains acyclic.
     * Otherwise, the Timer would never be garbage-collected and this
     * thread would never go away.
     */
    private TaskQueue queue;
    TimerThread(TaskQueue queue) {
        this.queue = queue;
    }
    public void run() {
        try {
            mainLoop();
        } finally {
            // Someone killed this Thread, behave as if Timer cancelled
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }
    /**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                // 从队列里面获取任务时要加锁
                synchronized(queue) {
                .........
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();// 执行任务
            } catch(InterruptedException e) {
            }
        }
    }
}


当任务在执行过程中抛出InterruptedException之外的异常时,唯一的消费线程就会因为抛出异常而终止,那么队列里的其他待执行的任务就会被清除


How to Fix


方法一 : run方法内最好使用try-catch结构捕捉可能的异常,不要把异常抛到run方法之外

所以在TimerTask的run方法内最好使用try-catch结构捕捉可能的异常,不要把异常抛到run方法之外。

5f615a97bd234ff291a20c73f09ef9a2.png


方法二: ScheduledThreadPoolExecutor (推荐)


其实要实现Timer功能,使用ScheduledThreadPoolExecutor的schedule是比较好的选择。如果ScheduledThreadPoolExecutor中的一个任务抛出异常,其他任务则不受影响。

public class TimerTest {
    public static void main(String[] args) throws InterruptedException {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        scheduledThreadPoolExecutor.schedule(()->{
            System.out.println("Task1 Running");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 模拟发生异常
            throw new RuntimeException();
        },1, TimeUnit.SECONDS);
        scheduledThreadPoolExecutor.schedule(()->{
            System.out.println("Task2 Running");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 关闭线程池
            scheduledThreadPoolExecutor.shutdown();
        },1, TimeUnit.SECONDS);
    }
}



之所以ScheduledThreadPoolExecutor的其他任务不受抛出异常的任务的影响,是因为在ScheduledThreadPoolExecutor中的ScheduledFutureTask任务中catch掉了异常 。


小结


ScheduledThreadPoolExecutor是并发包提供的组件,其提供的功能包含但不限于Timer。Timer是固定的多线程生产单线程消费,但是ScheduledThreadPoolExecutor是可以配置的,既可以是多线程生产单线程消费也可以是多线程生产多线程消费,所以在日常开发中使用定时器功能时应该优先使用ScheduledThreadPoolExecutor。

相关文章
|
3月前
|
安全 Java 容器
Java Review - Queue和Stack 源码解读
Java Review - Queue和Stack 源码解读
38 0
|
3月前
|
消息中间件 设计模式 Java
Java Review - Java进程内部的消息中间件_Event Bus设计模式
Java Review - Java进程内部的消息中间件_Event Bus设计模式
59 0
|
3月前
|
缓存 算法 安全
Java Review - 并发编程_前置知识二
Java Review - 并发编程_前置知识二
30 0
Java Review - 并发编程_前置知识二
|
3月前
|
算法 安全 Java
Java Review - 并发编程_ConcurrentLinkedQueue原理&源码剖析
Java Review - 并发编程_ConcurrentLinkedQueue原理&源码剖析
37 0
|
3月前
|
设计模式 安全 Java
Java Review - 并发编程_独占锁ReentrantLock原理&源码剖析
Java Review - 并发编程_独占锁ReentrantLock原理&源码剖析
39 0
|
3月前
|
安全 Java 程序员
Java Review - 并发编程_ThreadPoolExecutor原理&源码剖析
Java Review - 并发编程_ThreadPoolExecutor原理&源码剖析
35 0
|
3月前
|
算法 Java C++
Java Review - 并发编程_抽象同步队列AQS
Java Review - 并发编程_抽象同步队列AQS
27 0
|
3月前
|
算法 Java 容器
Java Review - HashMap & HashSet 源码解读
Java Review - HashMap & HashSet 源码解读
32 0
Java Review - HashMap & HashSet 源码解读
|
3月前
|
存储 Java
Java Review - PriorityQueue源码解读
Java Review - PriorityQueue源码解读
28 0
Java Review - PriorityQueue源码解读
|
3月前
|
前端开发 Java 容器
Java Review - LinkedList源码解读
Java Review - LinkedList源码解读
33 0