Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

A simple google shows up that

  • It was fixed in Java 5 if used a specific way (see Marko's answer)
  • Its still not good idea. Often a simple enum is better solution.

Instead of writing

public final class Singleton {
    // Double-check idiom for lazy initialization of instance fields.
    private static volatile Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        Singleton result = instance;
        if (result == null) { // First check (no locking)
            synchronized (Singleton.class) {
                result = instance;
                if (result == null) // Second check (with locking)
                    instance = result = new Singleton();
            }
        }
        return result;
    }
}

you can just write

public enum Singleton {
    // Thread safe lazy initialization of instance field.
    INSTANCE
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top