Unhandled exceptions with Java scheduled executors

前端 未结 4 2080
情歌与酒
情歌与酒 2020-12-24 13:16

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. E

4条回答
  •  鱼传尺愫
    2020-12-24 13:33

    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.

提交回复
热议问题