An empty infinite loop that does not do anything within the loop with an empty body is a suboptimal solution, and no code should use it. The solution is suboptimal because it consumes CPU cycles but does nothing. An optimizing compiler can Optimizing compilers and JITs are permitted to remove such a loop, and it which can lead to unexpected results. Consequently, use of 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 example.
...
Compliant Solution (sleep()
To avoid optimizing out of the loop, this compliant solution uses instructions that give up the CPU 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.
Code Block | ||
---|---|---|
| ||
public final int DURATION=10000; // in milliseconds public void nop() throws InterruptedException { while (true) { Thread.sleep(DURATION); } } |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2db72af44bd88d15-1a9b21c1-4a424fad-b398967c-e9202d9ef33fab9dcc0c40b5"><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> |
...