Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The Java Singleton pattern is a design pattern that governs the instantiation process. According to this design pattern, there can only be one instance of your class per JVM at any time. "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?]

The most usual A typical implementation of a Singleton in Java is done by having the creation of a single instance of the class as a static field.

You can create that instance 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.

...

When the getter method is called by two (or more) threads or classes simultaneously, multiple instances of the Singleton class might result if you neglect to use synchronization, which is a common mistake that happens with that implementationone neglects to synchronize access.

Code Block
bgColor#FFcccc
public 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 . . .
}

...

Compliant Solution

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

Code Block
bgColor#ccccff
public 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 . . .
}

...

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

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

Compliant Solution

Wiki Markup
It is still possible to create a copy of the Singleton object by cloning it using the object's {{clone}} method, which violates the Singleton Design Pattern's objective. To
prevent that you need to override the
 prevent this, one needs to override the object's {{clone
method, which throws a CloneNotSupportedException exception.
}} method and throw a {{CloneNotSupportedException}} exception from within it. \[[Daconta 03|AA. Java References#Daconta 03]\]

Code Block
bgColor#ccccff
public 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 . . .
}

See MSC05-J. Make your classes noncloneable unless required for more details about restricting the clone() method.

Wiki Markup
To be fully compliant, it must be ensured that the class obeys the _Singleton_ pattern's design contract. It is unreasonable to use the class for anything else, for example, as a method to share global state. \[[Daconta 03|AA. Java References#Daconta 03]\]

Risk Assessment

Using lazy initialization of in a Singleton without synchronizing the getInstance() method may lead to multiple instances and can thus violate the expected contract. 

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON33-J

low

unlikely

medium

P2

L3

...

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Chapter 17, Threads and Locks|http://java.sun.com/docs/books/jls/third_edition/html/memory.html]

Wiki Markup
\[[Fox 01|AA. Java References#Fox 01]\] [Sun Developer NetworkWhen is a Singleton not a Singleton?|http://java.sun.com/developer/technicalArticles/Programming/singletons/] 

Wiki Markup
\[[Daconta 03|AA. Java References#Daconta 03]\] Item 15: Avoiding Singleton Pitfalls;

...

CON32-J. Prefer notifyAll() to notify()      08. Concurrency (CON)      CON34-J. Avoid deadlock by requesting fine-grained locks in the proper order