I am using ScheduledExecutorService
to run threads at a fixed interval of 1 min
.
One instance of ScheduledExecutorService
runs one thread and another instance runs another thread.
Example:
ses1.scheduleAtFixRate(..) // for thread 1
ses2.scheduleAtFixRate(..) // for thread 2
I was encountering some exceptions by which the further execution stops. I want to catch the exception for a systematic shutdown of my application.
Should I handle the exception using a third thread that monitors both futures and handles the Exception or is there any other better way? Will it affect the other threads.
Any and all help is appreciated!
I was encountering some exceptions by which the further execution stops.
That is the expected behavior of ScheduledExecutorService.scheduleAtFixRate()
according to the specification :
If any execution of the task encounters an exception, subsequent executions are suppressed.
About your need :
I want to catch the exception for a systematic shutdown of my application.
Should I handle the exception using a third thread that monitors both futures and handles the Exception or is there any other better way?
Handling the future return with ScheduledFuture.get()
looks the right.
According to ScheduledFuture.scheduleAtFixedRate()
specification :
Otherwise, the task will only terminate via cancellation or termination of the executor.
So you don't even need to create a new scheduled future.
Just run two parallel tasks (with ExecutorService
or two threads is also possible) that wait on get()
of each Future
and that stops the application in case of exception thrown in the task :
Future<?> futureA = ses1.scheduleAtFixRate(..) // for thread 1
Future<?> futureB = ses2.scheduleAtFixRate(..) // for thread 2
submitAndStopTheApplicationIfFail(futureA);
submitAndStopTheApplicationIfFail(futureB);
public void submitAndStopTheApplicationIfFail(Future<?> future){
executor.submit(() -> {
try {
future.get();
} catch (InterruptedException e) {
// stop the application
} catch (ExecutionException e) {
// stop the application
}
});
}