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
rust
use axum::{extract::{Path, State}, http::StatusCode, Json}; use dashmap::DashMap; use serde::Serialize; use std::sync::Arc;
Request coalescing in an Axum handler
caching
concurrency
request-coalescing
Advanced
8 steps
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 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.