Measured on JDK 23: one exception stops scheduleAtFixedRate for good, and nothing is logged. Catch inside the task, check the future, and watch a heartbeat.
The job that stopped without a word
Belgavi's Book Store syncs stock levels from a supplier feed every few minutes. The job is a Runnable passed to ScheduledExecutorService.scheduleAtFixedRate, and it ran for months. One morning Tanishka noticed that stock on the site had not changed since the previous evening. The service was healthy, the thread pool was alive, and the log was clean. The supplier feed had returned an empty response once, the parser threw an IllegalStateException, and the job never ran again.
This is documented behaviour, and it surprises almost everyone the first time. This guide measures it on JDK 23, explains why nothing is logged, and gives three defences that work together: catch inside the task, observe the returned future, and watch a heartbeat from outside.
What the specification says
The Javadoc for both scheduleAtFixedRate and scheduleWithFixedDelay in JDK 23 lists the ways a periodic task ends: it is cancelled through its future, the executor terminates, or "an execution of the task throws an exception. In this case calling get on the returned future will throw ExecutionException, holding the exception as its cause. Subsequent executions are suppressed. Subsequent calls to isDone() on the returned future will return true."
So the exception is not lost. It is stored in the ScheduledFuture that the schedule call returned, and the task is not rescheduled. If nothing ever calls get() on that future, nobody sees the exception.
Measured on JDK 23.0.2
The companion probe schedules a synthetic stock-sync task every 50 ms that throws on its third run, observes for 600 ms, and prints what happened. It also installs a default uncaught-exception handler to see whether the exception reaches it.
java.version=23.0.2
scheduleAtFixedRate, no catch: runs=3 isDone=true isCancelled=false
future.get() -> java.lang.IllegalStateException: supplier feed returned no rows on run 3
scheduleWithFixedDelay, no catch: runs=3 isDone=true isCancelled=false
future.get() -> java.lang.IllegalStateException: supplier feed returned no rows on run 3
[stock-sync] run failed and was logged: supplier feed returned no rows on run 3
scheduleAtFixedRate, catching wrapper: kept running after run 3=true isDone=false
failures logged=1 (still scheduled: true)
heartbeat checker: job stopped after runs=3; stale heartbeat detected yes (threshold 3 periods = 150 ms)Three observations follow.
- With either scheduling method, the task ran exactly three times in 600 ms where it should have run about twelve. The future is done, not cancelled, and
get()returns the original exception as the cause. - The default uncaught-exception handler printed nothing. The executor's worker thread never saw an uncaught exception, because the scheduled task wrapper catches it and records it in the future. The thread goes back to the pool and stays healthy, which is why thread-pool metrics looked normal.
- The pool itself kept working. Other tasks on the same executor were unaffected.
Defence 1: catch inside the periodic task
The simplest fix is to make sure no RuntimeException escapes the task body. Wrap every periodic task once, at the point of scheduling, so individual jobs cannot forget:
static Runnable catching(String name, Runnable body, Logger log, AtomicInteger failures) {
return () -> {
try {
body.run();
} catch (RuntimeException e) {
failures.incrementAndGet();
log.log(Level.WARNING, name + " run failed; next run stays scheduled", e);
}
};
}
ScheduledFuture<?> f = scheduler.scheduleAtFixedRate(
catching("stock-sync", stockSync, log, failures), 0, 5, TimeUnit.MINUTES);The probe's wrapped variant logged one failure and kept running after run 3. Catch RuntimeException, not Throwable. An OutOfMemoryError or a StackOverflowError means the process is in a state where continuing on a timer is not obviously safe, and those should still end the task and be visible through the other defences.
Do not swallow silently. Count failures and log them with the exception, so a feed that fails on every run shows up as a rising counter rather than a quiet job doing nothing useful.
Defence 2: observe the future
Keep the ScheduledFuture and check it. A periodic task's future should never be done while the application expects it to run, so isDone() returning true is itself the alarm:
if (stockSyncFuture.isDone() && !stockSyncFuture.isCancelled()) {
try {
stockSyncFuture.get();
} catch (ExecutionException e) {
log.log(Level.SEVERE, "stock-sync stopped permanently", e.getCause());
health.markDown("stock-sync");
}
}This is the check to put in a readiness or health endpoint. It catches the case Defence 1 does not, an Error or an exception thrown by the wrapper itself, and it reports the real cause.
Defence 3: a heartbeat checked from outside
Both previous defences live inside the job's own code. A heartbeat checks the effect instead: the job records the time of its last successful run, and a separate checker compares it with the expected period. In the probe the checker used a threshold of three periods, 150 ms, and detected the stopped job. In production the threshold is usually a few periods, and the heartbeat is better exported as a metric such as "seconds since last successful stock sync", so an alert fires even if the whole process is wedged.
The heartbeat also catches failures that are not exceptions at all: a task blocked forever on a network read with no timeout, or a scheduler that was shut down during a reconfiguration. A fixed-rate task that blocks never starts its next run, because executions of one periodic task never overlap, and the Javadoc says later runs "may start late, but will not concurrently execute".
Choosing between fixed rate and fixed delay
The exception behaviour is identical for both. They differ in timing. scheduleAtFixedRate aims for start times at fixed intervals, so after a slow run the next ones start late and can bunch up. scheduleWithFixedDelay waits the delay after each run ends, so it never bunches. For a sync job that calls a remote feed, fixed delay is usually the better default: a slow supplier slows the job instead of making it fire back-to-back.
Shutdown and cancellation stop periodic tasks too
Exceptions are not the only way a periodic task ends quietly. ScheduledThreadPoolExecutor has two shutdown policies with different defaults. Existing periodic tasks are cancelled when shutdown() is called, because getContinueExistingPeriodicTasksAfterShutdownPolicy() is false by default, while existing one-shot delayed tasks still run, because getExecuteExistingDelayedTasksAfterShutdownPolicy() is true. A component that shares an executor with others and calls shutdown() during a reload therefore stops every periodic job on that executor, and the futures report isCancelled() rather than an exception.
Cancelled tasks also stay in the work queue until their scheduled time unless setRemoveOnCancelPolicy(true) is set, which matters for executors that schedule and cancel many timeouts. Give each long-lived periodic job an executor whose lifecycle matches the job, and make the health check in Defence 2 report a cancelled future as clearly as a failed one.
Where else the pattern hides
TimerandTimerTask, the older API, fail differently and more widely. In a quick check on the same JDK, one task that threw killed theTimerthread: a second, healthy task on the sameTimerstopped too, and scheduling anything afterwards threwIllegalStateException: Timer already cancelled. Unlike the executor, the exception was at least printed by the thread's default handler.- Frameworks that schedule methods for you, such as Spring's
@Scheduled, use their own error handlers. Read what yours does with a failed run; do not assume it matches the raw executor. CompletableFuturechains built on a timer have the same issue at every stage: an exception completes the stage exceptionally and later stages are skipped unless someone handles it.
Failure modes after the fix
Catching too much inside the loop. A wrapper that catches every failure and retries immediately turns a permanent error into a log flood. Keep the period as the retry interval and alert on the failure counter.
Losing the future. Code that discards the return value of scheduleAtFixedRate cannot ever perform Defence 2. Store it where the health check can see it.
Heartbeat measured at start rather than success. Recording the time at the top of the run reports a job that starts and fails every time as healthy. Record after the work succeeds.
Verification
The companion example's run.sh compiles the probe and compares its output with the recorded JDK 23 file, so a JDK that behaves differently fails the check. For your own services, add a test that schedules each periodic job with an injected failure on its first run and asserts that the job runs again and that the failure counter is one.