Loop Runs At Most Once
ID |
java.loop_runs_at_most_once |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Reliability |
Language |
Java |
Tags |
control-flow, loop, reliability |
Description
Reports a for, while or do-while loop whose body ends in an unconditional break, return or throw: a jump that always runs, so the loop can never reach a second iteration. Only the loop’s last direct statement is examined — a jump inside an if, a switch, a try, or a nested loop is conditional by construction and is not reported. A continue anywhere in the body that targets the loop, guarded or not, suppresses the report: it is direct evidence the loop was written to run more than once.
Rationale
A loop that cannot iterate reads as if it does, and is equivalent to a plain if. The usual cause is a jump statement written one level too high — meant to sit inside a condition, but placed directly in the loop body instead, so it fires on every entry rather than some of them.
int attempt = 0;
while (attempt < maxAttempts) {
processNextItem(queue);
attempt++;
break; // always runs -- the loop body executes exactly once
}