ScheduledExecutorService and failures

I am using the method <tt>ScheduledExecutorService.scheduleAtFixedRate</tt> to schedule a periodic task that I want to start and, essentially, forget. I expect this task to run until I stop it or shutdown the executor.

I have discovered the hard way that, if the Runnable I submitted experiences an exception, the executor will silently note the exception in the Future it provided at the time of scheduling and not execute the task again.

The above behavior seems reasonable. My problem with it is that I <b>need</b> that task to continue running. Yet, short of starting another periodic task to check on the first task, I see no easy way to detect that the task has failed and is no longer running. There is no way to listen for such failures that I can see.

What is the preferred way to handle errors in periodic tasks executed by an implementation of ScheduledExecutorService? The only solution I can see involves some non-trivial logic in the Runnable submitted that will detect errors and perform notifications. I'm hoping the concurrent APIs themselves can help me out! Any ideas?

-Bill

[1189 byte] By [balloniwa] at [2007-10-3 3:52:59]
# 1

Is finding this behaviour by trail-and-error actually harder than the more conventional way of reading it in the documentation?

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

Anyway... What's wrong with modifying your Runnable so that it doesn't allow any exceptions to leak out?

Or... write another Runnable that takes a Runnable as a parameter, and wraps the run() method and catches exceptions... like this (untested pseudo-ish-code):

public class ExceptionSafeRunnable implements Runnable {

public ExceptionSafeRunnable(Runnable r) {

this.runnable = r;

}

public void run() {

try {

r.run();

} catch (Throwable t) {

// log something here

}

}

}

Then you can do:

Runnable r = //... my runnable

r = new ExceptionSafeRunnable(r);

executor.scheduleAtFixedRate(...r...);

dannyyatesa at 2007-7-14 21:50:44 > top of Java-index,Core,Core APIs...