ScheduledExecutorService(下文简称SES)是j.u.c包中提供任务定时调度方法的接口,它的主要实现类就是调度线程池ScheduledThreadPoolExecutor,应用非常广泛,在我的上一篇拙作《修改ES IK插件源码,配合MySQL实现词库热更新》中就用到了它。
但特别需要注意,一旦SES执行的逻辑中抛出异常,那么调度会自动停止,并且不会有任何提示信息。在其scheduleWithFixedDelay()和scheduleAtFixedRate()方法的JavaDoc中,都有这样的描述:
If any execution of the task encounters an exception, subsequent executions are suppressed.
看了之后,不禁想对JUC世界的王Doug Lea说:
![195230-a93cc5aa770ce196.png](https://i-blog.csdnimg.cn/blog_migrate/ef49381e76f13322a5df00a37fdfab1d.png)
举个栗子吧。
public class SESExample {
public static void main(String[] args) {
ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor();
Random random = new Random();
pool.scheduleWithFixedDelay(() -> {
int i = random.nextInt(100);
System.out.println(i);
if (i % 5 == 0) {
throw new RuntimeException("Exception triggered! HAHA");
}
}, 1, 3, TimeUnit.SECONDS);
}
}
输出如下:
![195230-d49737ef7f395e32.png](https://i-blog.csdnimg.cn/blog_migrate/3d8053476627ab2b2fdcd998bbac41a1.png)
随机到90的时候抛出了RuntimeException,并且确实没有任何报错。要解决这个令人窒息的问题,有以下两种方法。
- try-catch大法好,永远都要检查异常
pool.scheduleWithFixedDelay(() -> {
try {
int i = random.nextInt(100);
System.out.println(i);
if (i % 5 == 0) {
throw new RuntimeException("Exception triggered! HAHA");
}
} catch (Throwable t) {
t.printStackTrace();
}
}, 1, 3, TimeUnit.SECONDS);
- 利用调度方法返回的ScheduledFuture对象
Runnable runnable = () -> {
int i = random.nextInt(100);
System.out.println(i);
if (i % 5 == 0) {
throw new RuntimeException("Exception triggered! HAHA");
}
};
ScheduledFuture future = pool.scheduleWithFixedDelay(runnable, 1, 3, TimeUnit.SECONDS);
try {
future.get();
} catch (InterruptedException | ExecutionException t) {
t.printStackTrace();
future = pool.scheduleWithFixedDelay(runnable, 1, 3, TimeUnit.SECONDS);
}
这两种方法都可以保证异常被捕获后继续调度,不会终止。但是如下这种方法呢?
ScheduledExecutorService pool = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler((t, e) -> {
e.printStackTrace();
});
return thread;
});
Random random = new Random();
pool.scheduleWithFixedDelay(() -> {
int i = random.nextInt(100);
System.out.println(i);
if (i % 5 == 0) {
throw new RuntimeException("Exception triggered! HAHA");
}
}, 1, 3, TimeUnit.SECONDS);
由实际测试可以得知,通过线程工厂ThreadFactory设置异常处理器UncaughtExceptionHandler是没有作用的,也就是说SES遇到异常时根本不会调用uncaughtException()方法,所以还是老老实实采用以上两种方法之一吧。
多嘴一句,关于这个问题,有一位国外的暴躁程序员在很久之前就写过,并且情绪十分激动,通篇传统美德。为了避嫌,只给出传送门,奇文共赏吧:http://code.nomad-labs.com/2011/12/09/mother-fk-the-scheduledexecutorservice/。
晚安晚安。