ScheduledExecutorService异常处理的正确姿势

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

举个栗子吧。

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

随机到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/

晚安晚安。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值