Spring Boot Scheduler with Java 21 Virtual Threads (Uptime Monitor Part 5)
Build the checker engine of a Spring Boot uptime monitor: @Scheduled polling, Java HttpClient and Java 21 virtual threads with short transactions. Part 5 of the UpCheck series.
Part 5 of the UpCheck series is the heart of the project: a scheduler that finds due monitors, checks them in parallel on virtual threads, and saves each result.
- Part 1: Project setup with MySQL and Docker
- Part 2: Database design with Flyway and JPA
- Part 3: REST API, validation and error handling
- Part 4: Spring Security with JWT
- Part 5: Scheduler with virtual threads (you are here)
- Part 6: Incidents and email alerts
- Part 7: Uptime stats, pagination and retention
- Part 8: Testing, Docker and deployment
Spring Boot scheduler with Java 21 virtual threads#
Today UpCheck comes alive: every 30 seconds a scheduler finds monitors that are due, checks them all in parallel, and saves each result. This is the heart of the project and the part interviewers will ask about most.
Design decisions#
| Problem | Solution |
|---|---|
| 500 sites, each may take 10 s to time out | One virtual thread per check: cheap, thousands are fine |
| Too many requests at once | A Semaphore caps it at 50 parallel checks |
| Two scheduler runs overlapping | fixedDelay: the next run starts only after the previous one ends |
| One bad monitor breaking the batch | Each result is saved in its own short transaction, errors are caught per monitor |
| Loading whole entities just for a URL | A JPQL projection loads only id and url |
Only the record() step touches the database inside a transaction, so a site that takes 10 seconds to time out never holds a connection.
Step 1: Find due monitors with SQL#
Add these two methods to MonitorRepository. The native query asks MySQL for active monitors that were never checked or whose interval has passed, using the idx_monitors_due index from Part 2.
package com.upcheck.monitor;
/** Lightweight projection used by the scheduler. */
public record CheckTarget(Long id, String url) {}
// add to MonitorRepository (imports: Query, Param, Instant, List)
@Query(value = """
SELECT m.id FROM monitors m
WHERE m.active = TRUE
AND (m.last_checked_at IS NULL
OR TIMESTAMPADD(MINUTE, m.interval_minutes, m.last_checked_at) <= :now)
ORDER BY m.last_checked_at IS NULL DESC, m.last_checked_at
LIMIT :limit
""", nativeQuery = true)
List<Long> findDueMonitorIds(@Param("now") Instant now, @Param("limit") int limit);
@Query("SELECT new com.upcheck.monitor.CheckTarget(m.id, m.url) FROM Monitor m WHERE m.id IN :ids")
List<CheckTarget> findCheckTargets(@Param("ids") List<Long> ids);
Step 2: HttpChecker, one GET request that never throws#
We use the JDK's built-in HttpClient, so no extra dependency. Status 200 to 399 counts as UP. Every failure (timeout, DNS error, refused connection, 5xx) becomes a CheckOutcome with a readable reason.
package com.upcheck.check;
import com.upcheck.config.AppProperties;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
@Component
public class HttpChecker {
private static final String USER_AGENT = "UpCheck/1.0 (+https://upcheck.dev)";
private final HttpClient client;
private final Duration timeout;
private final Clock clock;
public HttpChecker(AppProperties props, Clock clock) {
this.timeout = props.checker().requestTimeout();
this.clock = clock;
this.client = HttpClient.newBuilder()
.connectTimeout(timeout)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
}
public CheckOutcome check(String url) {
Instant startedAt = clock.instant();
long start = System.nanoTime();
try {
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(timeout)
.header("User-Agent", USER_AGENT)
.GET()
.build();
// discard the body: we only need the status and the timing
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
long elapsedMs = elapsedMs(start);
int code = response.statusCode();
return (code >= 200 && code < 400)
? CheckOutcome.success(code, elapsedMs, startedAt)
: CheckOutcome.httpFailure(code, elapsedMs, startedAt);
} catch (HttpConnectTimeoutException e) {
return CheckOutcome.error("Connection timed out", elapsedMs(start), startedAt);
} catch (HttpTimeoutException e) {
return CheckOutcome.error("Response timed out after " + timeout.toSeconds() + "s",
elapsedMs(start), startedAt);
} catch (IOException | IllegalArgumentException e) {
String reason = e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName();
return CheckOutcome.error(reason, null, startedAt);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return CheckOutcome.error("Check interrupted", null, startedAt);
}
}
private static long elapsedMs(long startNanos) {
return Duration.ofNanos(System.nanoTime() - startNanos).toMillis();
}
}
HttpConnectTimeoutException extends HttpTimeoutException, so it must be caught first.
Step 3: Save results (first version)#
For now, CheckService saves the result and updates the monitor's status. In Part 6 we extend it with incidents and email alerts.
package com.upcheck.check;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CheckResultRepository extends JpaRepository<CheckResult, Long> {
Page<CheckResult> findByMonitorIdOrderByCheckedAtDesc(Long monitorId, Pageable pageable);
// Part 7 adds aggregateSince and deleteOlderThan
}
package com.upcheck.check;
import com.upcheck.config.AppProperties;
import com.upcheck.monitor.Monitor;
import com.upcheck.monitor.MonitorRepository;
import com.upcheck.monitor.MonitorStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CheckService {
private static final Logger log = LoggerFactory.getLogger(CheckService.class);
private final MonitorRepository monitorRepository;
private final CheckResultRepository checkResultRepository;
private final int failureThreshold;
public CheckService(MonitorRepository monitorRepository,
CheckResultRepository checkResultRepository, AppProperties props) {
this.monitorRepository = monitorRepository;
this.checkResultRepository = checkResultRepository;
this.failureThreshold = props.checker().failureThreshold();
}
@Transactional
public void record(Long monitorId, CheckOutcome outcome) {
Monitor monitor = monitorRepository.findById(monitorId).orElse(null);
if (monitor == null || !monitor.isActive()) {
return; // deleted or paused while the HTTP call was running
}
checkResultRepository.save(new CheckResult(monitor, outcome));
MonitorStatus changedTo = monitor.recordCheck(outcome.up(), outcome.checkedAt(), failureThreshold);
if (changedTo != null) {
log.info("Monitor {} is now {}", monitorId, changedTo);
}
}
}
Step 4: The scheduler#
package com.upcheck.check;
import com.upcheck.monitor.CheckTarget;
import com.upcheck.monitor.MonitorRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
@Component
public class CheckScheduler {
private static final Logger log = LoggerFactory.getLogger(CheckScheduler.class);
private static final int BATCH_SIZE = 500;
private static final int MAX_PARALLEL_CHECKS = 50;
private final MonitorRepository monitorRepository;
private final HttpChecker httpChecker;
private final CheckService checkService;
private final Clock clock;
private final Semaphore permits = new Semaphore(MAX_PARALLEL_CHECKS);
public CheckScheduler(MonitorRepository monitorRepository, HttpChecker httpChecker,
CheckService checkService, Clock clock) {
this.monitorRepository = monitorRepository;
this.httpChecker = httpChecker;
this.checkService = checkService;
this.clock = clock;
}
// fixedDelay: the next run starts only after this one has finished, so runs never overlap
@Scheduled(fixedDelayString = "${upcheck.checker.poll-interval}", initialDelayString = "PT10S")
public void runDueChecks() {
List<Long> dueIds = monitorRepository.findDueMonitorIds(clock.instant(), BATCH_SIZE);
if (dueIds.isEmpty()) {
return;
}
List<CheckTarget> targets = monitorRepository.findCheckTargets(dueIds);
long start = System.currentTimeMillis();
// one cheap virtual thread per check; close() waits for all of them
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (CheckTarget target : targets) {
executor.submit(() -> checkOne(target));
}
}
log.info("Checked {} monitors in {} ms", targets.size(), System.currentTimeMillis() - start);
}
private void checkOne(CheckTarget target) {
try {
permits.acquire(); // cap concurrent outgoing requests and DB writes
try {
CheckOutcome outcome = httpChecker.check(target.url());
checkService.record(target.id(), outcome);
} finally {
permits.release();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
// e.g. optimistic lock conflict with a user edit: retried on the next poll
log.warn("Check failed for monitor {}: {}", target.id(), e.getMessage());
}
}
}
Why is the HTTP call outside the transaction? A database connection held for 10 seconds while waiting on a slow website would drain the pool of 10 connections in a moment. The slow part (network) happens first with no transaction; only the fast part (insert + update) runs inside record().
Running more than one instance? Each instance would run the scheduler. Add ShedLock with its JDBC provider so only one instance checks at a time.
Add a monitor with "intervalMinutes": 1. Within a minute you see Checked 1 monitors in ... ms in the log, and SELECT * FROM check_results shows rows. Add https://httpstat.us/503 to see a failing check.
Key takeaways#
- One poller asking the database who is due survives restarts and scales with an index.
- Virtual threads make waiting on slow websites cheap; a Semaphore caps the load.
- Keep the slow HTTP call outside the transaction so database connections are never held.