当前位置:首页 > 编程笔记 > 正文
已解决

ScheduledExecutorService的坑

来自网友在路上 147847提问 提问时间:2023-10-07 18:56:11阅读次数: 47

最佳答案 问答题库478位专家为你答疑解惑

参考文献

调度服务 ScheduledExecutorService 经常卡顿问题的排查及解决方法-腾讯云开发者社区-腾讯云

场景

        一个安顿广播程序使用的ScheduledExecutorService来定时执行任务,当有一个任务出现异常后就会卡住,不会继续执行后续的任务。

解决方案

查找定时运行的代码,捕获异常,当遇到错误时不影响后续任务执行。

/*** 样例代码
*/
private final ScheduledExecutorService es = Executors.newScheduledThreadPool(1);public void execute(AndonCallService andonCallService) {//10ms执行一次es.scheduleWithFixedDelay(() -> {andonCallService.andonCall();}, 0, 100, TimeUnit.MILLISECONDS);}

查看上面样例中使用的scheduleWithFixedDelay方法

源码注释中有这么一句:If any execution of the task encounters an exception, subsequent executions are suppressed.

翻译过来的意思就是:如果任务的任何执行遇到异常,则会抑制后续执行。

所以如果样例代码中andonCallService.andonCall();抛出任何异常就会导致任务卡住。

优化后代码

/*** 样例代码
*/
private final ScheduledExecutorService es = Executors.newScheduledThreadPool(1);public void execute(AndonCallService andonCallService) {//10ms执行一次es.scheduleWithFixedDelay(() -> {try{//新增异常处理andonCallService.andonCall();}catch (Exception e){log.error("执行调度任务发生异常,忽略此任务:{}", e.getMessage());}}, 0, 100, TimeUnit.MILLISECONDS);}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"ScheduledExecutorService的坑":http://eshow365.cn/6-16901-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!