Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: weakened the NCE so that it is actually vulnerable

...

Noncompliant Code Example (partial initialization)

ThreadClasses with thread-safe sub-objects (which may not be strictly immutable) must declare their not use nonfinal and nonvolatile 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 or final.

Code Block
bgColor#FFcccc
public class Container<K,V> {
  Map<K,V> map;

  public Container( void initialize() {
    if(map == null) {
      map = new HashMap<K,V>();	
    // Put values in 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 and object state.

Code Block
bgColor#ccccff
public class Container<K,V> {
  volatile Map<K,V> map;
  // ...
}

...