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

Compare with Current View Page History

« Previous Version 43 Next »

Declaring shared variables as volatile ensures visibility and limits reordering of accesses. Volatile accesses do guarantee the atomicity of composite operations such as incrementing a variable.

A write to a volatile field happens-before every subsequent read of that field. Statements that occur before the write to the volatile field also happen-before the read of the volatile field.

Declaring variables as volatile establishes a happens-before relationship such that a write to the volatile variable is always seen by a subsequent read. These operations appear to be sequentially consistent with respect to each other, although the code as a whole may not be sequential consistent. Consider two threads that are executing some statements:

Thread 1 and Thread 2 have a happens-before relationship such that Thread 2 does not start before Thread 1 finishes. This is established by the semantics of volatile accesses.

In this example, Statement 3 writes to a volatile variable, and statement 4 in the second thread, reads the same volatile variable. The read sees the most recent write (to the same variable v) from statement 3. This may not be true in the happens-before order because a future read can always see the default or previous value of v instead of the one set in the most recent write. This guarantee is provided by the sequential consistency property of volatile accesses.

Volatile read and write operations cannot be reordered with respect to each other and in addition, as required by the JMM, volatile read and write operations are also not reordered with respect to operations on nonvolatile variables. When reading the volatile variable, the other thread will also see statements occurring before the write to the volatile variable to have already executed, with prior occurrences of volatile and nonvolatile fields assuming the assigned values.

In the previous example, statement 4 also sees the statements 1 and 2 to have executed and all their operands with the most-up to date values. However, this does not mean that statements 1 and 2 are sequentially consistent with respect to each other. They may be freely reordered by the compiler. In fact, if statement 1 constituted a read of some variable x, it could see the value of a future write to x in statement 2.

Because the guarantees of code present before the volatile write are weaker than sequentially consistent code, volatile as a synchronization primitive, performs better. "Because no locking is involved, declaring fields as volatile is likely to be cheaper than using synchronization, or at least no more expensive. However, if volatile fields are accessed frequently inside methods, their use is likely to lead to slower performance than would locking the entire methods." [[Lea 00]].

"Finally, note that the actual execution order of instructions and memory accesses can be in any order as long as the actions of the thread appear to that thread as if program order were followed, and provided all values read are allowed for by the memory model. This allows the programmer to fully understand the semantics of the programs they write, and it allows compiler writers and virtual machine implementors to perform complex optimizations that a simpler memory model would not permit." [[JPL 06]].

The possible reorderings between volatile and nonvolatile variables are summarized in the matrix shown below. The load and store operations correspond to read and write operations that use the variable. [[Lea 08]]

Noncompliant Code Example (status flag)

This noncompliant code example uses a shutdown() method to set a non-volatile done flag that is checked in the run() method. If one thread invokes the shutdown() method to set the flag, it is possible that another thread might not observe this change. Consequently, the second thread may still observe that done is false and incorrectly invoke the sleep() method.

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

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

Compliant Solution (volatile status flag)

This compliant solution qualifies the done flag as volatile so that updates by one thread are immediately visible to another thread.

final class ControlledStop implements Runnable {
  private volatile boolean done = false;
  // ...
}

Noncompliant Code Example (nonvolatile guard)

This noncompliant code example declares a non-volatile int variable that is initialized in the constructor depending on a security check. In a multi-threading scenario, it is possible that the statements will be reordered so that the boolean flag initialized is set to true before the initialization has concluded. If it is possible to obtain a partially initialized instance of the class in a subclass using a finalizer attack (OBJ04-J. Do not allow partially initialized objects to be accessed), a race condition can be exploited by invoking the getBalance() method to obtain the balance even though initialization is still underway.

class BankOperation {
  private int balance = 0;
  private boolean initialized = false;
 
  public BankOperation() {
    if (!performAccountVerification()) {
      throw new SecurityException("Invalid Account"); 
    }
    balance = 1000;   
    initialized = true; 
  }
  
  private int getBalance() {
    if (initialized == true) {
      return balance;
    }
    else {
      return -1;
    }
  }
}

Compliant Solution (volatile guard)

This compliant solution declares the initialized flag as volatile to ensure that the initialization statements are not reordered.

class BankOperation {
  private int balance = 0;
  private volatile boolean initialized = false; // Declared volatile
  // ...
}

The use of the volatile keyword is inappropriate for composite operations on shared variables (CON01-J. Design APIs that ensure atomicity of composite operations and visibility of results).

Noncompliant Code Example (visibility)

This noncompliant code example consists of two classes, an immutable ImmutablePoint class and a mutable Holder class. Holder is mutable because a new ImmutablePoint instance can be assigned to it using the setPoint() method. If one thread updates the value of the ipoint field, another thread may still see the reference of the old value.

class Holder {
  ImmutablePoint ipoint;
  
  Holder(ImmutablePoint ip) {
   ipoint = ip;
  }
  
  ImmutablePoint getPoint() {
    return ipoint;
  }

  void setPoint(ImmutablePoint ip) {
    this.ipoint = ip;
  }
}

public class ImmutablePoint {
  final int x;
  final int y;

  public ImmutablePoint(int x, int y) {
    this.x = x;
    this.y = y;
  }
}

Compliant Solution (visibility)

This compliant solution declares the ipoint field as volatile so that updates are immediately visible to other threads.

class Holder {
  volatile ImmutablePoint ipoint;
  
  Holder(ImmutablePoint ip) {
    ipoint = ip;
  }
  
  ImmutablePoint getPoint() {
    return ipoint;
  }

  void setPoint(ImmutablePoint ip) {
    this.ipoint = ip;
  }
}

Note that no synchronization is necessary for the setPoint() method because it operates atomically on immutable data, that is, on an instance of ImmutablePoint.

Declaring immutable fields as volatile enables their safe publication, in that, once published, it is impossible to change the state of the sub-object.

Noncompliant Code Example (partial initialization)

Thread-safe classes (which may not be strictly immutable) must not use nonfinal and nonvolatile fields to ensure that no thread sees any field references before the sub-objects' initialization has concluded. This noncompliant code example does not declare the map field as volatile or final. Consequently, a thread that invokes the get() method may observe the value of field map before initialization has concluded.

public class Container<K,V> {
  Map<K,V> map;

  public synchronized void initialize() {
    if(map == null) {
      map = new HashMap<K,V>();	         
      // Fill some useful values into HashMap
    }
  }

  public V get(Object k) {
    if(map != null) {
      return map.get(k);
    } else {
      return null;
    }
  }
}

Compliant Solution (proper initialization)

This compliant solution declares the map field as volatile to ensure other threads see an up-to-date HashMap reference.

public class Container<K,V> {
  volatile Map<K,V> map;
  // ...
}

Risk Assessment

Failing to use volatile to guarantee visibility of shared values across multiple thread and prevent reordering of statements can result in unpredictable control flow.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON00- J

medium

probable

medium

P8

L2

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

[[JLS 05]] Chapter 17, Threads and Locks, section 17.4.5 Happens-before Order, section 17.4.3 Programs and Program Order, section 17.4.8 Executions and Causality Requirements
[[Tutorials 08]] Java Concurrency Tutorial
[[Lea 00]] Sections, 2.2.7 The Java Memory Model, 2.2.5 Deadlock, 2.1.1.1 Objects and locks
[[Bloch 08]] Item 66: Synchronize access to shared mutable data
[[Goetz 06]] 3.4.2. "Example: Using Volatile to Publish Immutable Objects"
[[JPL 06]] 14.10.3. "The Happens-Before Relationship"
[[MITRE 09]] CWE ID 667 "Insufficient Locking", CWE ID 413 "Insufficient Resource Locking", CWE ID 366 "Race Condition within a Thread", CWE ID 567 "Unsynchronized Access to Shared Data"


11. Concurrency (CON)      11. Concurrency (CON)      CON02-J. Always synchronize on the appropriate object

  • No labels