Executors and thread pools question 84 of 180 senior
What happens when a ScheduledExecutorService task throws?
- The next execution happens as normal
- Correct: The repeating schedule is cancelled silently, and nothing runs again until the process restarts
- The pool shuts down
- The exception is logged and the task retried
scheduleAtFixedRate and scheduleWithFixedDelay stop rescheduling if the task throws. The
ScheduledFuture completes exceptionally, and because nobody holds it, the failure is invisible. The
symptom is a heartbeat, a cache refresh or a cleanup job that "stopped working last Tuesday".
The fix is to make the task incapable of throwing:
scheduler.scheduleWithFixedDelay(() -> {
try {
refresh();
} catch (Throwable t) { // Throwable: an Error kills the schedule just as dead
log.error("refresh failed", t);
}
}, 0, 1, MINUTES);
While you are there: scheduleAtFixedRate measures from start to start, so if a run overruns the
period the next one begins immediately and they can pile up. scheduleWithFixedDelay measures from
end to start and cannot.
Quiz yourself on Executors and thread pools Suggest a correction