Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: replaced NCE with simpler synchronized keyword

...

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.

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

  public synchronized void initialize() {
    if(map == null) {
      synchronized(this) {
        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;
    }
  }
}

...