Learning Objectives
- Identify the code patterns that cause date iteration to loop forever
- Recognize the system-level symptoms of an infinite loop (CPU spike, timeout, unresponsive endpoint)
- Design safe test strategies for detecting infinite loops without hanging your test suite
How Date Loops Go Infinite
Many features iterate over a date range: generating daily reports, counting working days, building a calendar grid, or applying charges for each day of a rental period. The typical pattern looks like:
LocalDate current = startDate;
while (current.isBefore(endDate)) {
process(current);
current = current.plusDays(1); // correct: advances by 1 day each iteration
}
Bugs creep in when the step is wrong:
// Bug 1: step is 0 — current never advances
current = current.plusDays(0);
// Bug 2: negative step but wrong termination condition
// Should terminate when current < endDate but actually loops forever
LocalDate current = endDate;
while (current.isAfter(startDate)) {
process(current);
current = current.plusDays(1); // goes forward, never reaches startDate
}
// Bug 3: condition is satisfied on first evaluation but loop body resets it
while (!current.equals(endDate)) {
current = startDate; // resets to beginning every iteration
}
System Signatures of an Infinite Loop
When an endpoint is stuck in an infinite date loop, you will observe:
| Signal | What You See |
|---|---|
| CPU usage | Sustained 100% on one core (visible in top, Task Manager, or cloud metrics) |
| Response time | Request hangs indefinitely; no response until timeout |
| HTTP status | Eventually a 504 Gateway Timeout (load balancer kills the stuck request) |
| Server logs | No new log lines for the endpoint after the request was received |
| Thread dump | A single thread pinned on a while loop in date logic |
Timeout-Based Detection Strategy
You cannot wait for an infinite loop to finish — it never will. Use timeouts to detect them:
- Set a hard request timeout in your HTTP client (e.g., 10 seconds)
- Send the triggering request (e.g., a date range where start equals end, or end is before start)
- Expect a timeout or 504 — if the response arrives quickly, no loop occurred
- Monitor CPU on the server during the request — a spike that correlates with your request is a strong signal
- Report the hang time in your bug report: "Request sent at 14:03:21, timed out after 10 seconds, no response received"
Safe Loop Patterns
When reviewing or auditing code for loop safety, look for these safeguards:
- Guard clause before the loop:
if (!startDate.isBefore(endDate)) return emptyResult; - Maximum iteration cap:
int maxDays = 365 * 10; int count = 0; if (++count > maxDays) throw new IllegalStateException("Loop cap exceeded"); - Immutable step: the step value is a constant or final variable, not derived from user input