Search code examples
javamemory-model

Is double check issue fixed in 1.6 or 1.7?


There were a double check issue in 1.4 http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html Were it fixed in later JDKs?


Solution

  • No, it wasn't fixed and won't be fixed. Java 5 just made it clearly specified that this idiom is broken and that is the final verdict. The proper way to lazily initialize an instance field involves another, similarly called idiom: the double-check idiom:

    // Double-check idiom for lazy initialization of instance fields.
    private volatile FieldType field;
    FieldType getField() {
      FieldType result = field;
      if (result == null) { // First check (no locking)
        synchronized(this) {
          result = field;
          if (result == null) // Second check (with locking)
            field = result = computeFieldValue();
        }
      }
      return result;
    }
    

    Reference: Josh Bloch, Effective Java. See also this Oracle technetwork interview with Josh Bloch.