Lesson · Executors, Thread Pools & Async Programming
ScheduledExecutorService: delays, periods and the silent cancellation
16 min readScheduledExecutorService
A scheduler is a queue of deadlines with pool threads behind it. The two periodic forms measure their period from different points, and one thrown exception ends a periodic series for good while the returned future quietly records the failure. This lesson covers both shapes of period, the cancellation switches, and the traps that turn a heartbeat into a one-off.
Work that has to happen later
Some work has no caller. A cache has to be swept every few minutes, a heartbeat has to be sent while a connection looks idle, and an operation that hangs has to be abandoned after a deadline. None of these fit a request thread, and none of them belong to main.
The naive shape is a thread holding a sleep, and it costs three things at once: a thread per schedule, a cadence that drifts by however long each pass took, and no clean way to stop it, because a sleeping thread only wakes for an interrupt.
ScheduledExecutorService answers all three. You hand it a task plus a delay, it hands back a ScheduledFuture you can cancel, and the waiting itself costs no thread at all: the deadline sits in a queue until it is due.
import java.util.concurrent.*; ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2); ScheduledFuture<?> deadline = scheduler.schedule( () -> abortStuckRequest(), // runs once, after the delay 5, TimeUnit.SECONDS); deadline.cancel(false); // the operation finished in time: no need for the deadline
A scheduled task is the rest of the executor API plus a deadline. The delay decides when it becomes eligible, and the returned future is how you take it back.
Fixed rate or fixed delay: which mark the period is measured from
Both periodic forms run the same task again and again. The difference is the mark they measure from. scheduleAtFixedRate measures from the previous run's scheduled start, so the deadlines are initialDelay, initialDelay + period, initialDelay + 2 * period and so on. scheduleWithFixedDelay measures from the end of the previous run.
That single difference decides what happens when a run overruns its slot. Under fixed rate the next deadline has already passed, so the next run starts as soon as the previous one ends, and never before: a periodic task will not execute concurrently with itself. Under fixed delay the gap stays constant and everything after the long run shifts by the overrun.
Pick by asking which of the two you actually care about: a cadence (sample every five seconds, and treat lateness as lateness) or a gap (wait two minutes after the sweep finishes, because sweeps vary in cost).
| Form | Next run is measured from | When a run overruns its period | Use it for |
|---|---|---|---|
| scheduleAtFixedRate(task, initialDelay, period, unit) | the previous run's scheduled start, so deadlines form a grid | the next run starts as soon as the overrun ends, and later runs return to the grid | cadences: sampling, polling health, ticking counters |
| scheduleWithFixedDelay(task, initialDelay, delay, unit) | the end of the previous run | every following run shifts by the overrun, and the gap between runs does not change | work of unknown duration: sweeps, retries, heartbeats |
- Fixed rate with a period of 2s: the deadlines are 0, 2, 4, 6, 8, 10. The first three runs take 0.5s each and start on their deadlines.
- The fourth run starts at 6.0 and takes 3.0s, so it ends at 9.0, after its own next deadline of 8.0 has passed.
- The run due at 8.0 cannot overlap with it, so it starts at 9.0 the moment the overrun ends. That run is late, not skipped: the series has no missing executions.
- The following deadline is 10.0 and that run starts at 10.0. Because deadlines are counted from the schedule rather than from the late start, one long run does not shift a fixed rate series permanently.
- Fixed delay with the same delays and work: run 1 starts 0.0 and ends 0.5, so run 2 starts at 2.5 and ends at 3.0, run 3 starts at 5.0, run 4 starts at 7.5 and ends at 10.5, and run 5 waits for that end and starts at 12.5. Every later run moved right by the length of the long one.
Rate is measured from starts, delay from ends. Everything else about the two forms follows from that one sentence.
Periodic scheduling · one task, two sets of marks
the only difference is the point the 2s period is measured fromscheduleAtFixedRate · period 2s
The period is measured from the start the scheduler planned, so the deadlines keep a grid.
scheduleWithFixedDelay · delay 2s
The delay is measured from the moment the previous run ended, so a slow run shifts everything after it.
A throw in a periodic task completes the returned ScheduledFuture exceptionally and suppresses every later execution. No thread dies, no uncaught exception handler runs, and nothing is printed: the only evidence is the future, which is why the series belongs in a try/catch and the handle belongs somewhere a health check can read it.
What the executor is actually made of
Executors.newScheduledThreadPool(n) returns a ScheduledThreadPoolExecutor: a pool whose work queue orders tasks by deadline instead of arrival order. When a worker is free it takes the earliest due task; when nothing is due it waits for the next deadline or for a new registration.
The pool size is the concurrency of your schedule. With n > 1, two different scheduled tasks can be due at the same moment and run at once, while one periodic task still never overlaps with itself. Executors.newSingleThreadScheduledExecutor() is the safe default when scheduled work touches state without locking, because every scheduled task passes through one thread in deadline order, and that wrapper additionally refuses reconfiguration, so nobody can grow it later by accident.
The default thread factory creates non-daemon threads (the daemon-threads lesson covers the exit gate), so a scheduler nobody shuts down keeps the JVM alive. Give housekeeping work a factory that names and daemonizes its threads, or shut the scheduler down with the rest of the application.
- The pool never grows past its core size. The deadline queue is unbounded, so there is no pressure that would justify another thread: the size you pass is the maximum concurrency, not a starting point.
- A delay makes a task eligible, not punctual. If every worker is busy with long work, a due task waits for a thread, and it is never early.
- Periods are relative delays, not calendar times. The scheduler tracks its deadlines on a monotonic clock, so an adjusted wall clock does not move them, and there is no expression for at 03:00 local time.
- A period or delay of zero or less is rejected with IllegalArgumentException at the call itself, while an initial delay of zero or less simply means now.
The scheduler is a queue of deadlines with pool threads behind it: it promises order and eligibility, never a moment of execution.
The trap: a periodic series ends silently on the first throw
Here is the failure that makes this lesson worth reading. If a periodic task throws, the executor does not retry, does not log, and does not keep the series alive: subsequent executions are suppressed. One bad row in a cache sweep stops every future sweep, and nothing appears on stderr, because the throwable was captured rather than thrown.
Where does it go? Into the ScheduledFuture the registration returned. That future completes exceptionally, and once it is complete the series is over. If nobody holds it, the cancellation is invisible, which is the same silent storage you met with submit earlier (the uncaught-exception-handler lesson covers that routing), now applied to a schedule.
The working rule is short. Wrap the body of every periodic task in a try/catch, log with context, and let the series continue. A periodic task is a small background service: it is supposed to survive bad data, because nothing else will restart it.
scheduler.scheduleAtFixedRate(() -> { try { sweepCache(); // the part that can fail on one bad row } catch (RuntimeException e) { log.warning("sweep failed, schedule kept: " + e); // the series survives } }, 0, 30, TimeUnit.SECONDS);
- The failure is stored, not reported. No handler chain runs and no worker dies: the throwable becomes the future's outcome, exactly as with submit.
- Keep the ScheduledFuture anyway. A health check that reads it (isDone, or a timed get in a monitor) is what turns a silently stopped series into a visible incident.
- Catch around the work, not around the call. The try/catch has to be inside the task body; wrapping the registration only protects the act of scheduling.
- One bad minute is the same event as one bad row. Any throwable ends the series, so decide deliberately what the task should do with each kind of failure.
A thrown exception silently ends every future run: catch inside the task.
Schedule lab · same task, four schedules
pick a scenarioRuns 1 to 3 start on the grid at 0.0, 2.0 and 4.0. Run 4 starts at 6.0 and takes 3.0s, so it overruns its own next deadline of 8.0. A periodic task never overlaps with itself, so the run due at 8.0 starts at 9.0, the moment the overrun ends. The following deadline of 10.0 is met exactly, because deadlines are counted from the schedule rather than from the late start: the grid absorbs the overrun.
Stopping it: cancel(false) against cancel(true)
The ScheduledFuture returned by a periodic registration is a handle for the whole sequence rather than for one run. Cancelling it stops future runs, there is no partial cancel, and there is no un-cancel.
cancel(false) means do not interrupt: a run in progress is allowed to finish, the next one never happens, and a task that has not started never starts. cancel(true) means interrupt if running: the executing thread gets its interrupt flag set, and the task stops only where it cooperates and checks (the interrupt rules belong to the thread API lesson).
| Call | Task not started yet | Task currently running | Returns |
|---|---|---|---|
| cancel(false) | never runs, and is removed from eligibility | finishes its current run, no further runs happen | true if the outcome was still undecided |
| cancel(true) | same as false, since there is nothing to interrupt | the running thread is interrupted, and the task decides whether to stop | true if the outcome was still undecided |
| cancel on a completed or already cancelled future | no effect | no effect | false: the outcome is already decided |
- A cancelled future answers get() with CancellationException. That is how code awaiting the series learns it will never arrive.
- Cancel the deadline you no longer need. A one-shot timeout that is still registered will fire its action later; cancelling it when the operation finished in time is what keeps a stale timeout out of a completed workflow.
- Cancelled tasks linger in the queue until their deadline by default. A
ScheduledThreadPoolExecutorcan be told to drop them immediately with setRemoveOnCancelPolicy(true), which matters when a service registers many short-lived deadlines.
Cancellation is a request with one switch: false leaves the running task alone, true sets the flag on its thread.
What the schedule promises, and what it does not
Two claims are worth pinning down before this API turns into a surprise. The scheduler promises order and eligibility, not punctuality: a deadline makes a task eligible, and a free pool thread decides when it actually runs. A periodic task never overlaps with itself, in either form.
- Lateness comes from outside the schedule. Pool availability, JVM scheduling and GC pauses all delay a run, and none of them are compensated in advance.
- A loop with a sleep has the same cadence rule as fixed delay, measuring from the end of the work, but it owns a thread and it cannot express the fixed rate rule at all, because it has no separate idea of a deadline.
- Only fixed rate can return to its grid. Its next deadline was computed while the slow run was still going, so the run after the late one is due on the original grid again.
- Sharing the pool matters. A long one-shot task on a one-thread scheduler delays everything due behind it, including periodic runs: use separate pools for classes of work rather than one pool for everything.
The deadline decides eligibility; the pool decides the moment.
Heartbeats, sweeps and deadlines
Three shapes cover most real uses, and each one picks a form for a reason.
- Heartbeat every 30 seconds: fixed delay. The cost of one ping should not make the next one early or let two pile up, so the gap between attempts is the contract.
- Cache sweep: fixed delay. The sweep duration varies with the data, and the requirement is a quiet period between sweeps rather than a frequency.
- Sample or tick: fixed rate. The consumer wants points on a regular grid, so the schedule is measured from the schedule. The rule that keeps it honest is making the sampled work cheap.
- Deadline for a slow operation: one-shot schedule plus cancel. Register the timeout action, cancel it when the operation finishes in time, and let it fire only when it did not.
- Retry with backoff: reschedule, do not fix. A fixed rate retry keeps hammering a service that is already down; schedule the next attempt from the catch block with the next delay, which also keeps one permanent failure from becoming a permanent series.
Every periodic task is a small background service: make its body defensively boring, and keep its handle.
The rules in one place
The API surface is three calls, one of which exists mostly to be cancelled.
- Schedule once with
schedule, periodically withscheduleAtFixedRate(measured from starts) orscheduleWithFixedDelay(measured from ends). - Wrap the periodic body in a try/catch, or decide deliberately that the series ends on the first failure.
- Cancel with false for a switch-off, and with true when the current run must be interrupted and its body checks the flag.
- Close the scheduler with the application, or name and daemonize its threads so a forgotten scheduler cannot keep the JVM alive.
Rate from starts, delay from ends, and nothing runs again after an uncaught throw.
One throw, and the series is gone
A periodic task that throws has its future completed exceptionally and all subsequent executions suppressed: no handler runs, nothing prints, and the schedule looks fine from the outside. Wrap the periodic body in try/catch and keep the returned ScheduledFuture where a health check can read it. The failure you cannot see is the one that stops the heartbeat.
Interview angles
What is the difference between scheduleAtFixedRate and scheduleWithFixedDelay?+
Fixed rate counts the period from the previous scheduled start, so the deadlines form a grid. Fixed delay waits the given delay after the previous run ends, so the cadence stretches with the work. A run that overruns under fixed rate is followed immediately by the next one, never in parallel with it.
Follow-up: Which of the two drifts when the work is slower than the period?
What happens when a periodic task throws?+
Subsequent executions are suppressed, and the future returned by the registration completes exceptionally. No uncaught exception handler runs and nothing is printed, so a stopped series stays invisible unless the task caught its own failures or somebody reads the future.
Common misconception: People expect the scheduler to report the failure the way a worker thread handler would. Nothing reports it: the throwable is stored as the future's outcome.
How do you stop a periodic task, and what does cancel(true) actually do?+
cancel on the returned future stops the series as a unit. false lets a run in progress finish and suppresses the rest; true also sets the interrupt flag on the executing thread, which only helps where the task checks it.
A periodic future is a handle for the sequence, not for one run. Cancelling a completed or already cancelled task returns false, and a cancelled future answers get() with CancellationException.
How is this better than a while loop with a sleep in it?+
The loop measures work plus sleep, so its cadence drifts with the work, and it owns a thread per schedule. The scheduler keeps deadlines in a shared queue, gives every registration a cancellation handle, and can express fixed rate, which a loop cannot.
What the loop does have is simplicity, and inside a single dedicated daemon thread it is not wrong. What it cannot do is share one waiting mechanism across many deadlines, or hand you an object that stops a series.
Does a scheduled task run exactly on its deadline?+
No. The deadline makes it eligible, and the pool decides the moment: busy workers delay it, and it never starts early. It also never runs concurrently with itself, in either periodic form.
Which pool does newScheduledThreadPool use, and why does the size matter?+
A ScheduledThreadPoolExecutor, whose queue orders tasks by deadline, so the pool never grows past the core size you passed. That size is the concurrency between different scheduled tasks, while a single periodic task stays sequential with itself.
The default thread factory creates non-daemon threads, so a scheduler you forget to shut down keeps the JVM alive. The single-thread variant is a wrapper that serializes tasks in deadline order and cannot be reconfigured to use more threads.