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说:


举个栗子吧。

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);
    }
}

输出如下:


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

晚安晚安。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容