ScheduledExecutorService遇到异常后续任务不继续执行的问题

    近写了个程序,程序中使用到了ScheduledExecutorService的scheduleAtFixedRate方法,用于定时执行任务,但是发现程序运行一段时间之后定时任务不执行了,查看日志和perfcounter都没有看到任何异常,比较郁闷。最后看了一下JDK的源码,在源码的Java doc中的发现了如下一句话If any execution of the task encounters an exception, subsequent executions are suppressed.Otherwise, the task will only terminate via cancellation or termination of the executor.

简单总结就是:如果定时任务执行过程中遇到发生异常,则后面的任务将不再执行。
       我们可以做个实验验证一下:

package zmx.jdkthreadpool.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test {
	
    private final static ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) {
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                int[] s = new int[1];
                System.out.println("OK");
                System.out.println(s[1]);  // 数组越界
            }
        }, 0, 2, TimeUnit.SECONDS);
    }


}


 

执行结果:

OK


        可以看到定时任务只执行了一次,因为第一次执行就遇到了数组越界异常,后面的任务被取消了。

        对上面代码进行修改:

package zmx.jdkthreadpool.test;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Test {
	
    private final static ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) {
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    int[] s = new int[1];
                    System.out.println("OK");
                    System.out.println(s[1]); // 数组越界
                } catch (Throwable t) {
                    System.out.println("Error");
                }

            }
        }, 0, 2, TimeUnit.SECONDS);
    }


}


执行效果:

OK
Error
OK
Error
OK
Error
OK
Error


加了try/catch之后可以看到定时任务没有被取消。

  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值