An infinite loop with an empty body is a suboptimal solution because it consumes CPU cycles but does nothing. Optimizing compilers and JITs are permitted to remove such a loop, which can lead to unexpected results. Consequently, programs must not include infinite loops with empty bodies.
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 example.
public int nop() { while (true) {} }
Compliant Solution (Thread.sleep()
)
This compliant solution avoids use of a meaningless infinite loop by sleeping the current thread within the while loop. The loop body contains semantically meaningful operations and consequently cannot be optimized away.
public final int DURATION=10000; // in milliseconds public void nop() throws InterruptedException { while (true) { Thread.sleep(DURATION); } }
Compliant Solution (yield()
)
This compliant solution invokes Thread.yield()
, which causes the thread running this method to consistently defer to other threads.
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="314e9aba-6c02-4b3e-ad95-9c4b199b8a00"><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> |
MSC00-J. Use SSLSockets rather than Sockets for secure data exchange 49. Miscellaneous (MSC)