java 47 lines · 6 steps

A safe recurring heartbeat scheduler in Java

How a single-thread scheduled executor runs a repeating task safely and swaps cleanly when restarted.

Explained by highlit
1import java.time.Duration;
2import java.util.concurrent.Executors;
3import java.util.concurrent.ScheduledExecutorService;
4import java.util.concurrent.ScheduledFuture;
5import java.util.concurrent.TimeUnit;
6import java.util.concurrent.atomic.AtomicReference;
7 
8public final class HeartbeatScheduler {
9 
10 private final ScheduledExecutorService scheduler =
11 Executors.newSingleThreadScheduledExecutor(runnable -> {
12 Thread thread = new Thread(runnable, "heartbeat");
13 thread.setDaemon(true);
14 return thread;
15 });
16 
17 private final AtomicReference<ScheduledFuture<?>> handle = new AtomicReference<>();
18 
19 public void start(Runnable task, Duration interval) {
20 ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(
21 () -> runSafely(task),
22 interval.toMillis(),
23 interval.toMillis(),
24 TimeUnit.MILLISECONDS);
25 
26 ScheduledFuture<?> previous = handle.getAndSet(future);
27 if (previous != null) {
28 previous.cancel(false);
29 }
30 }
31 
32 private void runSafely(Runnable task) {
33 try {
34 task.run();
35 } catch (RuntimeException ex) {
36 System.getLogger(HeartbeatScheduler.class.getName())
37 .log(System.Logger.Level.WARNING, "heartbeat failed", ex);
38 }
39 }
40 
41 public void shutdown() throws InterruptedException {
42 scheduler.shutdown();
43 if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
44 scheduler.shutdownNow();
45 }
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom ThreadFactory lets you name threads and mark them daemon so they never block JVM shutdown.
  2. 2Wrapping a scheduled task in a try/catch keeps one failure from silently killing the entire repeating schedule.
  3. 3AtomicReference.getAndSet swaps state and returns the old value in one step, making restart logic race-free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A safe recurring heartbeat scheduler in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code