Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The assumption that thread suspension and yielding flush the cached registers and reload the values when execution resumes, is misleading and paves the way for potential coding errors.

Noncompliant Code Example

Wiki Markup
This noncompliant code example declares a non-volatile {{Boolean}} flag. "The compiler is free to read the field {{this.done}} just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of {{this.done}}." \[[JLS 05|AA. Java References#JLS 05]\].

Code Block
bgColor#FFCCCC
private Boolean done;
while (!this.done) {
  Thread.sleep(1000);
}

Compliant Solution

This compliant solution declares the flag volatile to ensure that updates to it are seen immediately across multiple threads.

Code Block
bgColor#ccccff
private volatile Boolean done;
while (!this.done) {
  Thread.sleep(1000);
}

Risk Assessment

Relying on the synchronization semantics of Thread.yield() and Thread.sleep() methods can cause unexpected behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON44- J

low

probable

medium

P4

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] section 17.9 "Sleep and Yield"

...