Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added NCE/CS for use of volatile with objects

...

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

Noncompliant Code Example

Thread-safe objects must declare their nonfinal fields as volatile 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.

Code Block
bgColor#FFcccc

public class Container<K,V> {
  Map<K,V> map;
  final int size = 1000;

  public Container() {
    map = new HashMap<K,V>();	
    // Put values in HashMap
  }

  public V get(Object k) {
    return map.get(k);
  }
}

Compliant Solution

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

Code Block
bgColor#ccccff

public class Container<K,V> {
  volatile Map<K,V> map;
  final int size = 1000;

  // ...
}

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.

...