Infinite loop Medium

Use loop control flow to ensure that loops are exited, even if exceptional behaviors are encountered. If an operation is retried in a loop, then a retry counter or timeout should be used to ensure that the loop eventually terminates.

Detector ID
java/infinite-loop@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public String loopControlNoncompliant() {
2    ResultClass resultClass = new ResultClass();
3    // Noncompliant: does not have loop control flow to prevent an infinite loop.
4    for ( ; ; ) {
5        try {
6            String result = resultClass.getResult();
7            return result;
8        } catch (TimeoutException e) {
9            resultClass.retry();
10        }
11    }
12}

Compliant example

1public String loopControlCompliant() {
2    ResultClass resultClass = new ResultClass();
3    // Compliant: has loop control flow to prevent an infinite loop.
4    for (int i = 0; i < 10; ++i) {
5        try {
6            String result = resultClass.getResult();
7            return result;
8        } catch (TimeoutException e) {
9            resultClass.retry();
10        }
11    }
12    return null;
13}