Versions Compared

Key

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

2.1 VNA00-J. Ensure visibility when accessing shared primitive variables

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, the thread may observe a stale value of the shared variable. To ensure the visibility of the most recent update, either the variable must be declared volatile or the reads and writes must be synchronized.
Declaring a shared variable volatile guarantees visibility in a thread-safe manner 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 reads and writes of other variables. (For more information, see guideline “VNA02-J. Ensure that compound operations on shared variables are atomic.")
The first condition can be relaxed when you can be sure that only one thread will ever update the value of the variable Goetz 2006. However, code that relies on a single-thread confinement is error-prone and difficult to maintain. This behavior is permissible under this guideline but not recommended.
Synchronizing the code makes it easier to reason about its behavior and is frequently more secure than simply using the volatile keyword. However, synchronization has a somewhat higher performance overhead and can result in thread contention and deadlocks when used excessively.
Declaring a variable volatile or correctly synchronizing the code guarantees that 64-bit primitive long and double variables are accessed atomically. (For more information on sharing those variables among multiple threads, see guideline “VNA05-J. Ensure atomicity when reading and writing 64-bit values.")

2.1.1 Noncompliant Code Example (Non-

...

Volatile Flag)

This noncompliant code example uses a shutdown() method to set a non-volatile done flag that is checked in the run() method.

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) { 
        // Handle exception
        Thread.currentThread().interrupt(); // Reset interrupted status
      } 
    } 	 
  }

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

If one thread invokes the shutdown() method to set the flag, a second thread might not observe that change. Consequently, the second thread may observe that done is still false and incorrectly invoke the sleep() method. A compiler is allowed to optimize the code if it determines that the value of done is never modified by the same thread, resulting in an infinite loop.

...

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

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

If one thread invokes the shutdown() method to set the flag, a second thread might not observe that change. Consequently, the second thread may observe that done is still false and incorrectly invoke the sleep() method. A compiler is allowed to optimize the code if it determines that the value of done is never modified by the same thread, resulting in an infinite loop.

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

...