Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2021.1

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 with an empty body consumes CPU cycles but does nothing. An optimizing compiler can Optimizing compilers and just-in-time systems (JITs) are permitted to (perhaps unexpectedly) remove such a loop, and it 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 this example.

Code Block
bgColor#FFCCCC

public int nop() {
  while (true) {}
}

Compliant Solution (Thread.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 invoking Thread.sleep() within the while loop. The loop body contains semantically meaningful operations and consequently cannot be optimized away.

Code Block
bgColor#ccccff

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
bgColor#ccccff

public void nop() {
  while (true) {
    Thread.yield();
  }
}

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC01-J

low

Low

unlikely

Unlikely

medium

Medium

P2

L3

Related Guidelines

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="625ed222-930e-4aad-bdc8-c4852f1fb1bc"><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

ToolVersionCheckerDescription
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.MSC01.EBAvoid control statements with empty bodies
SonarQube3.10S2189

Bibliography


...

Image Added Image Added MSC00-J. Use SSLSockets rather than Sockets for secure data exchange      49. Miscellaneous (MSC)