Java Concurrency Interview

Executors and thread pools question 84 of 180 senior

What happens when a ScheduledExecutorService task throws?

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.

executors scheduling

Quiz yourself on Executors and thread pools Suggest a correction