Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: initialize on demand reference should be final

...

This noncompliant code example uses a non-private constructor for instantiating a singleton.

Code Block
bgColor#FFcccc

class MySingleton {
  private static MySingleton Instance;

  protected MySingleton() {    
    Instance = new MySingleton();
  }

  public static synchronized MySingleton getInstance() {    
    return Instance;
  }
}

...

This compliant solution reduces the accessibility of the constructor to private and immediately initializes the field Instance, allowing it to be declared final. Singleton constructors must be private.

Code Block
bgColor#ccccff

class MySingleton {
  private static final MySingleton Instance = new MySingleton();

  private MySingleton() {    
    // private constructor prevents instantiation by untrusted callers
  }

  public static synchronized MySingleton getInstance() {    
    return Instance;
  }
}

...

Multiple instances of the Singleton class can be created when the getter method is tasked with initializing the singleton when necessary, and the getter method is invoked by two or more threads simultaneously.

Code Block
bgColor#FFcccc

class MySingleton {
  private static MySingleton Instance;

  private MySingleton() {    
    // private constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static MySingleton getInstance() { // Not synchronized
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }
}

...

Multiple instances can be created even when the singleton construction is encapsulated in a synchronized block.

Code Block
bgColor#FFcccc

public static MySingleton getInstance() {
  if (Instance == null) {
    synchronized (MySingleton.class) {
      Instance = new MySingleton();
    }
  }
  return Instance;
}

...

To address the issue of multiple threads creating more than one instance of the singleton, make getInstance() a synchronized method.

Code Block
bgColor#ccccff

class MySingleton {
  private static MySingleton Instance;

  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }
}

...

Another compliant solution for implementing thread-safe singletons is the correct use of the double-checked locking idiom.

Code Block
bgColor#ccccff

class MySingleton {
  private static volatile MySingleton Instance;

  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  // Double-checked locking
  public static MySingleton getInstance() {
    if (Instance == null) {
      synchronized (MySingleton.class) {
        if (Instance == null) {
          Instance = new MySingleton();
        }
      }
    }
    return Instance;
  }
}

...

This compliant solution uses a static inner class to create the singleton instance.

Code Block
bgColor#ccccff

class MySingleton {
  static class SingletonHolder {
    static final MySingleton Instance = new MySingleton();
  }

  public static MySingleton getInstance() {
    return SingletonHolder.Instance;
  }
}

...

This noncompliant code example implements the java.io.Serializable interface, which allows the class to be serialized. Deserialization of the class implies that multiple instances of the singleton can be created.

Code Block
bgColor#FFcccc

class MySingleton implements Serializable {
  private static final long serialVersionUID = 6825273283542226860L;
  private static MySingleton Instance;

  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }
}

...

Adding a readResolve() method that returns the original instance is insufficient to enforce the singleton property. This is insecure even when all the fields are declared transient or static.

Code Block
bgColor#FFcccc

class MySingleton implements Serializable {
  private static final long serialVersionUID = 6825273283542226860L;
  private static MySingleton Instance;

  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }

  private Object readResolve() {
    return Instance; 
  }
}

At runtime, an attacker can add a class that reads in a crafted serialized stream:

Code Block

public class Untrusted implements Serializable {
  public static MySingleton captured;
  public MySingleton capture;
  
  public Untrusted(MySingleton capture) {
    this.capture = capture;
  }

  private void readObject(java.io.ObjectInputStream in)
                          throws Exception {
    in.defaultReadObject();
    captured = capture;
  }
}

The crafted stream can be generated by serializing the following class:

Code Block

public final class MySingleton
                   implements java.io.Serializable {
  private static final long serialVersionUID =
      6825273283542226860L;
  public Untrusted untrusted =
      new Untrusted(this); // Additional serial field
 
  public MySingleton() { }
}

...

This serializable noncompliant code example uses a non-transient instance field str.

Code Block
bgColor#FFcccc

class MySingleton implements Serializable {
  private static final long serialVersionUID =
      2787342337386756967L;
  private static MySingleton Instance;
  
  // non-transient instance field 
  private String[] str = {"one", "two", "three"}; 
                 
  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  public void displayStr() {
    System.out.println(Arrays.toString(str));
  }
 
  private Object readResolve() {
    return Instance;
  }
}

...

Bloch [Bloch 2008] suggests the use of an enumeration type as a replacement for traditional implementations when serializable singletons are indispensable.

Code Block
bgColor#ccccff

public enum MySingleton {
  ; // empty list of enum values

  private static MySingleton Instance;

  // non-transient field
  private String[] str = {"one", "two", "three"};

  public void displayStr() {
    System.out.println(Arrays.toString(str));
  }	 
}

...

When the singleton class implements java.lang.Cloneable directly or through inheritance, it is possible to create a copy of the singleton by cloning it using the object's clone() method. This noncompliant code example shows a singleton that implements the java.lang.Cloneable interface.

Code Block
bgColor#FFcccc

class MySingleton implements Cloneable {
  private static MySingleton Instance;

  private MySingleton() {
    // private constructor prevents
    // instantiation by untrusted callers
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }
}

...

When the singleton class must indirectly implement the Cloneable interface through inheritance, the object's clone() method must be overridden with one that throws a CloneNotSupportedException exception [Daconta 2003].

Code Block
bgColor#ccccff

class MySingleton implements Cloneable {
  private static MySingleton Instance;

  private MySingleton() {
    // private constructor prevents instantiation by untrusted callers
  }

  // Lazy initialization
  public static synchronized MySingleton getInstance() {
    if (Instance == null) {
      Instance = new MySingleton();
    }
    return Instance;
  }

  public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }
}

...

A static singleton becomes eligible for garbage collection when its class loader becomes eligible for garbage collection. This usually happens when a nonstandard (custom) class loader is used to load the singleton. This noncompliant code example prints different values of the hash code of the singleton object from different scopes.

Code Block
bgColor#FFcccc

  {
  ClassLoader cl1 = new MyClassLoader();
  Class class1 = cl1.loadClass(MySingleton.class.getName());
  Method classMethod = 
      class1.getDeclaredMethod("getInstance", new Class[] { });
  Object singleton = classMethod.invoke(null, new Object[] { });
  System.out.println(singleton.hashCode());
}

ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod = 
    class1.getDeclaredMethod("getInstance", new Class[] { });
Object singleton = classMethod.invoke(null, new Object[] { } );
System.out.println(singleton.hashCode());

...

This compliant solution demonstrates this technique. It prints a consistent hash code across all scopes. It uses the ObjectPreserver class [Grand 2002] described in rule TSM02-J. Do not use background threads during class initialization.

Code Block
bgColor#ccccff

 {
  ClassLoader cl1 = new MyClassLoader();
  Class class1 = cl1.loadClass(MySingleton.class.getName());
  Method classMethod = 
      class1.getDeclaredMethod("getInstance", new Class[] { });
  Object singleton = classMethod.invoke(null, new Object[] { });
  ObjectPreserver.preserveObject(singleton); // Preserve the object
  System.out.println(singleton.hashCode());
}

ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod = 
    class1.getDeclaredMethod("getInstance", new Class[] { });
// Retrieve the preserved object
Object singleton = ObjectPreserver.getObject();  
System.out.println(singleton.hashCode());

...

[Bloch 2008]

Item 3. Enforce the singleton property with a private constructor or an enum type; and Item 77. For instance control, prefer enum types to readResolve

[Daconta 2003]

Item 15. Avoiding singleton pitfalls

[Darwin 2004]

9.10 Enforcing the Singleton Pattern

[Fox 2001]

When Is a Singleton Not a Singleton? 

[Gamma 1995]

Singleton

[Grand 2002]

Chapter 5, Creational Patterns, Singleton

[JLS 2005]

Chapter 17, Threads and Locks

 

      49. Miscellaneous (MSC)