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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom ThreadFactory lets you name threads and mark them daemon so they never block JVM shutdown.
- 2Wrapping a scheduled task in a try/catch keeps one failure from silently killing the entire repeating schedule.
- 3AtomicReference.getAndSet swaps state and returns the old value in one step, making restart logic race-free.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-safe-recurring-heartbeat-scheduler-in-java-explained-java-e3da/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.