Heuristic:APIJSON APIJSON Demo Double Checked Locking Process Supervisor
| Knowledge Sources | |
|---|---|
| Domains | Concurrency, Process_Management, Reliability |
| Last Updated | 2026-10-14 00:00 GMT |
Overview
Use double-checked locking with a volatile process reference and synchronized block to prevent duplicate Node.js process launches during concurrent health check and scheduler threads.
Description
The AutoTestNodeProcessSupervisor.ensureRunning() method uses the double-checked locking pattern to prevent race conditions when multiple threads detect the Node.js process as unreachable. The first check (isNodeServiceReachable()) is unsynchronized — a fast path that avoids locking when the process is healthy. If unreachable, the thread acquires the lock monitor and re-checks reachability (the second check), preventing duplicate process launches when the @Scheduled keepAlive thread and the ApplicationReadyEvent listener run concurrently. The process field is volatile, ensuring visibility across threads.
Usage
Apply this heuristic when a managed process can be started from multiple concurrent triggers (e.g., scheduled health checks + event listeners). Use volatile + double-checked locking to ensure exactly one process launch.
The Insight (Rule of Thumb)
- Action: Check
isNodeServiceReachable()before the synchronized block; re-check inside the block. - Value:
volatile Process process+synchronized(lock). - Trade-off: Minimal overhead for the fast path (no lock when healthy); correct serialization only when restart is needed.
- Compatibility: Works with any JVM threading model; the
volatileensures theprocessreference is visible to all threads.
Reasoning
Without double-checked locking, two threads could simultaneously pass the first reachability check, both acquire the lock sequentially, and each launch a duplicate process. The second check inside the synchronized block catches this: after the first thread launches the process and exits the lock, the second thread enters, re-checks reachability (now true), and returns without launching. The volatile keyword on process prevents the JVM from reordering reads/writes, ensuring the reference is always current across CPU caches.
Code Evidence
Double-checked locking from `AutoTestNodeProcessSupervisor.java:71-90`:
public void ensureRunning() {
if (!autoTestEnabled || !enabled || isNodeServiceReachable()) { // First check (no lock)
return;
}
synchronized (lock) {
if (isNodeServiceReachable()) { // Second check (under lock)
return;
}
Process current = process;
if (current != null && current.isAlive()) {
waitUntilReachable();
return;
}
startProcess();
waitUntilReachable();
}
}
Volatile field declarations from `AutoTestNodeProcessSupervisor.java:24-25`:
private final Object lock = new Object();
private volatile Process process;
private volatile Path logFilePath;