Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: removed a condition from when to use volatile, edits

Reading a shared primitive variable in one thread may not yield the value of the most recent write to the variable from another thread. Consequently, multiple threads may observe stale values of the shared variable and fail to perform the necessary actions on a timely basis. Visibility of the most recent update can be ensured by declaring the variable as volatile or correctly synchronizing the reads and writes to the variable.

The use of volatile is safe under a very restrictive set of conditions, all of which must holdDeclaring a shared variable volatile guarantees thread-safety only when both of the following conditions are met:

  • A write to a variable does not depend on its current value
  • A write to a variable does not depend on the result of any non-atomic compound operations involving that involve reads and writes of other variables Locking is not required for any other reason (all actions are atomic(see CON01-J. Ensure that compound operations on shared variables are atomic for more information)

Wiki Markup
The first condition is sometimes relaxed when it can be ensured that only one thread ever updates the value of the variable \[[Goetz 06|AA. Java References#Goetz 06]\]. However, it is still possible for reader threads to see stale values of the variable while the writing thread is in the process of modifying its value, before writing it back. Furthermore, it is hard to maintain code that relies on an invariant such as single-thread confinement to be true at all times.

...

Code Block
bgColor#FFcccc
final class ControlledStop implements Runnable {
  private boolean done = false;
 
  @Override public void run() {
    while (!done) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handleHandle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done = true;
  }
}

...

This compliant solution declares the done flag as volatile so to ensure that updates are become visible to other threads.

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private volatile boolean done = false;
 
  public void run() {
    while (!done) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handleHandle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public void shutdown() {
    done = true;
  }
}

...

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

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private final AtomicBoolean done = new AtomicBoolean(false);
 
  public void run() {
    while (!done.get()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handleHandle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

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

...

This compliant solution uses the intrinsic lock of the Class object to ensure that updates are become visible to other threads.

Code Block
bgColor#ccccff
final class ControlledStop implements Runnable {
  private boolean done = false;
 
  public void run() {
    while (!isDone()) {
      try {
        // ...
        Thread.currentThread().sleep(1000); // Do something
      } catch(InterruptedException ie) { 
        // handleHandle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

  public synchronized boolean isDone() {
    return done;
  }

  public synchronized void shutdown() {
    done = true;
  }
}

...

  • Performance: Intrinsic locks cause threads to block temporarily and may introduce some contention; volatile incurs no blocking.
  • Deadlock: Excessive synchronization can make the program deadlock prone.

...