Versions Compared

Key

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

...

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 . . .
}

By applying a static modifier to the getInstance()method which returns the Singleton, allows the method to be accessed subsequently without creating a new object.

Noncompliant Code Example

Anther solution for Singletons to be thread-safe is the double-checked locking. It is not guaranteed to work because compiler optimizations can make 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();
     }
   }
 }
}


Risk Assessment

To guarantee the liveness of a system, the method notifyAll() should be called rather than notify().

...