An empty infinite loop that does not do anything within the loop 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 remove such a loop, and it can lead to unexpected results.
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 could remove the while loop in the example.
public int nop() { while (true) {} }
Compliant Solution (sleep()
To avoid optimizing out of the loop, this compliant solution uses instructions that give up the CPU within the while loop.
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="51e62b89-e21a-483d-b586-7e70092c3141"><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)