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

Compare with Current View Page History

« Previous Version 12 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 nonvolatile 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]]. This occurs because there is no {BB. Definitions#happens-before order|happens-before relation] offered by Thread.sleep().

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. The volatile flag provides a {BB. Definitions#happens-before order|happens-before relation] between this thread and any thread that sets done.

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"


CON15-J. Ensure actively held locks are released on exceptional conditions      11. Concurrency (CON)      CON17-J. Avoid using ThreadGroup APIs

  • No labels