0

I have an application that uses a ScheduledExecutorService to handle multiple Runnable: each one is scheduled at fixed rate and must be alive as long as the application.

I need a solution to be notified if any of those threads is terminated for some exception, so I can schedule them again.

Can I use any pattern for this problem? Or am I using the wrong objects in my application?

Marco Stramezzi
  • 2,143
  • 4
  • 17
  • 37
  • http://stackoverflow.com/questions/21442322/scheduledexecutorservice-check-if-scheduled-task-has-already-been-completed – Ravindra babu Mar 31 '16 at 15:56

2 Answers2

0

It might be easier if you simply wrap the Runnable so that exceptions never cause the task to be cancelled:

class CatchingRunnable implements Runnable {
  private final Runnable delegate;

  CatchingRunnable(Runnable delegate) {
    this.delegate = delegate;
  }

  @Override public void run() {
    try {
      delegate.run();
    } catch (RuntimeException e) {
      // Handle the exception somehow, e.g. log it.
    }
  }
}

Now schedule runnable via:

executor.scheduleAtFixedRate(new CatchingRunnable(runnable), delay, period, unit);

Then you never need to worry about rescheduling them.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • This is good, but it might be difficult to predict any kind of exception you can have and handle it accordingly. Suggestion: from the ```catch``` block, call back to the class that has the executor, and reschedule. To do that, you will probably have another interface instead of ```Runnable``` for ```delegate```, that also has a function (e.g. ```recreate()```) to recreate the same delegate. – Jorn Vernee Mar 31 '16 at 16:12
  • @JornVernee well, sure, you might want to handle specific exceptions in specific ways. But 1) how would you handle those "unknowable" exceptions by some other means? 2) If your goal is "if it failed, restart it", the type of the exception doesn't matter. – Andy Turner Mar 31 '16 at 16:14
  • Yes, my point was number 2, the type of exception doesn't matter. The suggestion was to have the runnable reschedule itself if it terminates with an exception. That is all. – Jorn Vernee Mar 31 '16 at 16:18
0

You alternatively could maintain a handler to resubmit if the ScheduleFuture completes.

bszeliga
  • 128
  • 11