You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 4 Next »

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

CERT C Secure Coding Standard: MSC40-C. Do not use an empty infinite loop

Bibliography

[API 2006]


SER03-J. Prevent serialization of unencrypted, sensitive data      16. Serialization (SER)      SER05-J. Do not allow serialization and deserialization to bypass the Security Manager

  • No labels