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, programs must not include infinite loops with empty bodies.
...
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) {} } |
...
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; // in milliseconds
public void nop() throws InterruptedException {
while (true) {
// Useful operations
Thread.sleep(DURATION);
}
}
|
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8ad58d981cf29ee0-0b9f8951-425b4226-b8c682f3-716181ee649078530ceceac4"><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> |
...