Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Deleted void related guideline (MSC40-C)

...

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 this example.

Code Block
bgColor#FFCCCC

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

...

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();
  }
}

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MSC01-J

low Low

unlikely Unlikely

medium Medium

P2

L3

...

Bibliography

[API 20062014]

 

...