You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 33 Next »

The singleton design pattern's intent is succinctly described by the seminal work of [[Gamma 95]]:

Ensure a class only has one instance, and provide a global point of access to it.

"Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets." [When is a Singleton not a Singleton?]. Other applications of singletons involve maintaining performance statistics, system monitoring and logging, implementing printer spoolers or as simple as ensuring that only one audio file plays at a time.

A typical implementation of the Singleton pattern in Java is the creation of a single instance of the Singleton class that encloses a private static instance field.

The instance can be created using lazy initialization, which means that the instance is not created when the class loads but when it is first used.

Noncompliant Code Example

When the getter method is called by two (or more) threads or classes simultaneously, multiple instances of the Singleton class might result if one neglects to synchronize access.

class MySingleton {
  private static MySingleton _instance;

  private MySingleton() {
    // construct object . . .
    // private constructor prevents instantiation by outside callers
  }

  // lazy initialization
  // error, no synchronization on method access

  public static MySingleton getInstance() {
    if (_instance == null) {
     _instance = new MySingleton();
    }
    return _instance;
  }

  // Remainder of class definition . . .
}

Noncompliant Code Example

Multiple instances can be created even if you add a synchronized(this) block to the constructor call.

// Also an error, synchronization does not prevent
// two calls of constructor.
public static MySingleton getInstance() {
 if (_instance == null) {
   synchronized (MySingleton.class) {
      _instance = new MySingleton();
   }
 }
 return _instance;
}

Compliant Solution

To avoid these issues, make getInstance() a synchronized method.

class MySingleton {

  private static MySingleton _instance;

  private MySingleton() {
    // construct object . . .
    // private constructor prevents instantiation by outside callers
  }

   // lazy initialization
   public static synchronized MySingleton getInstance() {
     if (_instance == null) {
       _instance = new MySingleton();
     }
     return _instance;
   }
   // Remainder of class definition . . .
}

Applying a static modifier to the getInstance() method which returns the Singleton allows the method to be accessed subsequently (after the initial call) without creating a new object.

Noncompliant Code Example

Another solution for Singletons to be thread-safe is double-checked locking. Unfortunately, it is not guaranteed to work because compiler optimizations can force the assignment of the new Singleton object before all its fields are initialized.

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

Noncompliant Code Example

The other range of Singleton related subtleties involve object serialization and cloning. Serialization allows objects to be constructed without invoking the constructor and in turn allows object replication. It is also possible to create a copy of the Singleton object by cloning it using the object's clone method whenever the Singleton class implements Cloneable directly or through inheritance. Both these conditions violate the Singleton Design Pattern's guarantees.

Compliant Solution

It is recommended that Singleton classes be made non-serializable. As a precautionary measure, (serializable) classes must never save a reference to a singleton object in its instance variables. The getInstance method should be used instead, whenever access to the object is required.

To address the cloning issue, do not make the Singleton class cloneable. If it indirectly implements the Cloneable interface through inheritance, override the object's clone method and throw a CloneNotSupportedException exception from within it. [[Daconta 03]]

class MySingleton {
  private static MySingleton _instance;

  private MySingleton() {
    // construct object 
    // private constructor prevents instantiation by outside callers
  }

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

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

  // Remainder of class definition 
}
  • No labels