0

I've got a problem. I've got some code that looks like this:

executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("Exec"));
[...]
executor.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
// my task
...
}, 1, 1, TimeUnit.MINUTES);

And every once in a while the said task encounters a problem and crashes. And the newSingleThreadScheduledExecutor has an interesting property: it dies silently and won't execute the task again.

I need to modify that behavior. In other words, even if run() encounters a RuntimeException, I want the task to continue executing at the fixed rate.

How do I do that?

Peter Donegan
  • 43
  • 1
  • 9

1 Answers1

2

I need to modify that behavior. In other words, even if run() encounters a RuntimeException, I want the task to continue executing at the fixed rate.

The simplest approach would be to create a wrapper Runnable:

public final class ExceptionSwallowingRunnable implements Runnable {
    private final Runnable delegate;

    public ExceptionSwallowingRunnable(Runnable delegate) {
        // TODO: Argument validation
        this.delegate = delegate;
    }

    @Override public void run() {
        try {
            delegate.run();
        } catch (RuntimeException e) {
            // Logging etc
        }
    }
}

Then just run that in the scheduled executor, wrapping your real task. Note that you could potentially catch Throwable instead, if you really want to catch everything - I wouldn't recommend that though.

There may be an alternative approach, but this was the simplest one I could think of with no further research :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Reasonable idea. I wonder if anybody has written an ExecutorService that always wraps the Runnable thusly? Call it the "JasonExecutorService" cause it can't be killed. :-) – user949300 Sep 29 '12 at 19:34