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

Compare with Current View Page History

« Previous Version 9 Next »

According to the Java Language Specification [[JLS 05]], section 17.9 "Sleep and Yield":

It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

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

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]].

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.

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

CON16- 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

[[JLS 05]] section 17.9 "Sleep and Yield"


CON22-J. Use the correct form of the double-checked locking idiom      11. Concurrency (CON)      12. Methods (MET)

  • No labels