An infinite loop with an empty body is a suboptimal solution, because it consumes CPU cycles but does nothing. Optimizing compilers and just-in-time systems (JITs) are permitted to (perhaps unexpectedly) remove such a loop, which can lead to unexpected results. Consequently, use of programs must not include infinite loops with empty bodies is forbidden.
Noncompliant Code Example
This noncompliant code example implements an idle task that continuously executes a loop without executing any instructions within the loop. An optimizing compiler or JIT could remove the while
loop in the this example.
Code Block | ||
---|---|---|
| ||
public int nop() {
while (true) {}
}
|
Compliant Solution (Thread.sleep()
)
This compliant solution avoids use of a meaningless infinite loop by sleeping the current thread invoking Thread.sleep()
within the while
loop. The loop body contains semantically meaningful operations , and consequently cannot be optimized away.
Code Block | ||
---|---|---|
| ||
public final int DURATION=10000; // inIn milliseconds public void nop() throws InterruptedException { while (true) { // Useful operations Thread.sleep(DURATION); } } |
...
This compliant solution invokes Thread.yield()
, which causes the thread running this method to consistently defer to other threads.:
Code Block | ||
---|---|---|
| ||
public void nop() {
while (true) {
Thread.yield();
}
}
|
Risk Assessment
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC01-J |
Low |
Unlikely |
Medium | P2 | L3 |
Related Guidelines
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="af2146ad-6cb8-48d1-853b-41ab43eda144"><ac:plain-text-body><![CDATA[ | [[API 2006 | https://www.securecoding.cert.org/confluence/display/java/AA.+Java+References#AA.JavaReferences-API06]] | ]]></ac:plain-text-body></ac:structured-macro> |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Parasoft Jtest |
| CERT.MSC01.EB | Avoid control statements with empty bodies | ||||||
SonarQube | 3.10 | S2189 |
Bibliography
[API 2014] |
...
MSC00-J. Use SSLSockets rather than Sockets for secure data exchange 49. Miscellaneous (MSC)