Video in progress
How do scheduleAtFixedRate and scheduleWithFixedDelay differ in ScheduledExecutorService, and what happens if the task throws an exception?
FixedRate runs the task on a strict schedule by start times, while FixedDelay runs it with a set pause after the previous run finishes. With both, if the task throws, all later runs are silently cancelled.
📖 Answer
ScheduledExecutorService ses = Executors.newScheduledThreadPool(2);
// every 10 seconds by start time: 0, 10, 20, 30...
ses.scheduleAtFixedRate(this::pushMetrics, 0, 10, TimeUnit.SECONDS);
// a 10 second pause after the previous run ends: if the work takes 4 s, that's 0, 14, 28...
ses.scheduleWithFixedDelay(this::syncCatalog, 0, 10, TimeUnit.SECONDS);
With FixedRate, if one run takes longer than the period (say 15 s), the next one starts late, but the same task never runs in parallel with itself. The ones that fell behind run back to back, "catching up". For things like polling an external system or synchronization, FixedDelay is usually safer.
The most dangerous part is the exception. The Javadoc is explicit: if a task terminates with an exception, subsequent executions are suppressed. There's nothing in the log, because the error stays inside the ScheduledFuture. In prod it looks like this: the cache refresh stopped one day and nobody noticed.
ses.scheduleWithFixedDelay(() -> {
try {
syncCatalog();
} catch (Exception e) {
log.error("katalog sinxronizatsiyasi yiqildi", e); // the schedule stays alive
}
}, 0, 10, TimeUnit.SECONDS);
Two more details: in ScheduledThreadPoolExecutor the number of threads equals the core size and the queue is unbounded, so maximumPoolSize has no effect on it. And in a single-thread scheduler, one slow task delays all the others too.
Spring's @Scheduled runs on top of this same mechanism, but it logs an exception from a repeating task and keeps the schedule going.
Sign up to mark studied questions and save your progress.