Heuristic:APIJSON APIJSON Demo AtomicBoolean Preventing Overlap Scheduled Runs
| Knowledge Sources | |
|---|---|
| Domains | Concurrency, Testing, Reliability |
| Last Updated | 2026-10-14 00:00 GMT |
Overview
Use AtomicBoolean.compareAndSet(false, true) to prevent overlapping scheduled regression test runs when a previous test run exceeds the cron interval.
Description
The AutoTestRegressionScheduler uses an AtomicBoolean running field to guard against overlapping test executions. When the cron scheduler fires, runScheduledApiRegression() attempts running.compareAndSet(false, true). If the previous run is still in progress (running is already true), the CAS fails and the new invocation logs a warning and returns immediately. The flag is reset to false in a finally block, ensuring it is always cleared even if the test execution throws an exception.
Usage
Apply this heuristic when a scheduled task can run longer than its cron interval. Use AtomicBoolean with compareAndSet to skip overlapping runs rather than queuing them, which would consume memory and produce stale results.
The Insight (Rule of Thumb)
- Action: Guard the scheduled method with
running.compareAndSet(false, true); reset infinally. - Value: Skip (not queue) if a previous run is still active.
- Trade-off: A test run may be skipped if the previous one runs long, but this prevents resource exhaustion and conflicting test state.
- Compatibility:
AtomicBooleanis lock-free and thread-safe; works across multiple scheduler threads.
Reasoning
The cron schedule runs at 10:00 and 20:00, but a regression test can take up to 180 minutes (configurable timeout). If a test run exceeds the interval, the next cron trigger would start a parallel test run — consuming double the resources, conflicting with the shared Node.js process, and producing interleaved test reports. The AtomicBoolean guard ensures only one test run is active at any time. The compareAndSet operation is atomic, preventing the race where two threads both read false and both proceed. The finally block is critical: without it, an exception would leave running = true permanently, blocking all future runs.
Code Evidence
AtomicBoolean guard from `AutoTestRegressionScheduler.java:48,82-85`:
private final AtomicBoolean running = new AtomicBoolean(false);
// In runScheduledApiRegression():
if (!running.compareAndSet(false, true)) {
Log.w(TAG, "已有 API 回归测试任务在执行,跳过本次调度");
return;
}
Reset in finally block from `AutoTestRegressionScheduler.java:96-100`:
try {
sendReportEmail(result);
} finally {
running.set(false);
}
The Chinese warning message 已有 API 回归测试任务在执行,跳过本次调度 means "An API regression test task is already executing, skipping this scheduled run".