Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added CS courtesy Tim Halloran

...

However, synchronization is a more secure alternative in situations where the volatile keyword is inappropriate, such as if a variable's new value depends on its old value. Refer to CON01-J. Do not assume that composite operations are atomic and CON07-J. Do not assume that a grouping of calls to independently atomic methods is atomic for more details.

Compliant Solution (java.util.concurrent.atomic.AtomicBoolean)

This compliant solution uses an AtomicBoolean flag to ensure that updates are visible to other threads.

Code Block
bgColor#ccccff

final class ControlledStop implements Runnable {
  private AtomicBoolean done = new AtomicBoolean(false);
 
  public void run() {
    while (!done.get()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handle exception
      } 
    } 	 
  }

  protected void shutdown() {
    done.set(true);
  }
}

Risk Assessment

Failing to ensure visibility of shared primitive variables on accesses can lead to a thread seeing stale values of the variables.

...