Java预定执行程序的未处理的异常 [英] Unhandled exceptions with Java scheduled executors

查看:142
本文介绍了Java预定执行程序的未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题,我想知道究竟发生了什么。我正在使用Java的 ScheduledExecutorService 每五分钟运行一次任务。它工作得很好执行者完全改变了我在Java中进行线程编程的方式。



现在,我浏览了Java文档,了解如果计划任务失败,未处理的行为将是什么行为例外,但找不到任何东西。



下一个计划的任务是否仍然运行?如果存在未处理的异常,则计划执行者将停止调度任务?任何人都可以指出有关这个简单问题的信息?



非常感谢。

解决方案>

scheduleAtFixedRate scheduleWithFixedDelay 的Javadoc表示如果执行任务遇到异常,后续执行被压制。我并没有发现这是完全清楚的,但似乎说如果你的运行方法抛出任何种类的异常,那么调度程序将有效地删除该任务。通过该调度程序运行的任何其他任务不应受到影响。不应该很难测试它实际上是什么...



取消任务可能不一定是坏事。如果运行方法抛出一个 RuntimeException ,那么它可能在某处有一个错误,而且系统的状态是未知的。但至少我建议在运行方法中捕获 RuntimeException ,并在SEVERE中记录完整的堆栈跟踪。您可能希望根据具体情况重新启动任务。但是无论哪种方式,您都需要登录才能找出出错的机会。


I have the following issue and I would like to know what exactly happens. I am using Java's ScheduledExecutorService to run a task every five minutes. It works very well. Executors completely changed the way I do thread programming in Java.

Now, I browsed Java Doc for information about what would be the behavior in case the scheduled task fails with an unhandled exception, but couldn't find anything.

Is the next scheduled task still going to run? If there is an unhandled exception, the scheduled executor stops scheduling task? Can anyone point to information regarding this simple issue?

Thanks a lot.

解决方案

The Javadoc of both scheduleAtFixedRate and scheduleWithFixedDelay says "If any execution of the task encounters an exception, subsequent executions are suppressed." I don't find that to be exactly crystal clear, but it seems to be saying that if your run method throws any kind of exception, then the scheduler will effectively drop that task. Any other tasks running via that scheduler should not be affected. It shouldn't be hard to test what it actually does...

Cancellation of the task may not necessarily be a bad thing. If the run method throws a RuntimeException, it's probably got a bug somewhere, and the state of the system is unknown. But at minimum I would advise catching RuntimeException in your run method, and logging the full stack trace at SEVERE. You may want to then rethrow to cancel the task, depending on the circumstances. But either way you'll need the logging to have a fighting chance of working out what went wrong.

这篇关于Java预定执行程序的未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆