Unhandled exceptions with Java scheduled executors

Pablo Santa Cruz picture Pablo Santa Cruz · Nov 2, 2009 · Viewed 16.4k times · Source

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.

Answer

Lachlan picture Lachlan · Nov 2, 2009

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.