Singleton < Javapedia < TWiki

TWiki . Javapedia . Singleton

Home | Help | Changes | Index | Search | Go

Singleton

http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

Or even:

http://www.google.com/search?q=double+checked+locking+is+broken&ie=utf-8&oe=utf-8&rls=Swiftfox:en-US:unofficial&client=firefox-a

/**
 * A class of which at most one instance
 * can exist per VM.
 *
 * Use Singleton.getInstance() to access this
 * instance.
 */
public class Singleton {
   /**
    * The constructor could be made private
    * to prevent others from instantiating this class.
    * But this would also make it impossible to
    * create instances of Singleton subclasses.
    */
   protected Singleton() {
     // ...
   }

   /**
    * A handle to the unique Singleton instance.
    */
   static private Singleton instance = null;

   /**
    * @return The unique instance of this class.
    */
   static public Singleton getInstance() {
      if(null == instance) {
         instance = new Singleton();
      }
      return instance;
   }

   /**
    * This version of the method will assure that one and only one 
    * instance is created in a multithreaded environment.
    *
    * @return The unique instance of this class
    */
   static public Singleton getThreadSafeInstance() {
      if (null == instance) {
         synchronized(Singleton.class) {
            if (null == instance) {
               instance = new Singleton();
            }
         }
      }
      return instance;
   }
   
   // ...additional methods omitted...
}


Also See


Articles



Discussion about Singleton

It is not possible in Java to have "A class of which at most one instance can exist per VM." The best that you can do is one instance per classloader. This has particularly serious effects on applets. -- DougPardee 12-Jun-03

The implementation above incorporates a classic mistake, because it is not thread-safe. The everyday type of Singleton can be implemented much more easily in Java than by trying to reproduce the C++ code from the GoF book:

  public class Singleton {
      public static final instance = new Singleton();
      // constructor and instance methods
  }
There is no need for a "getter" because we can define the static attribute to be final. There is no need for the fancy (but not thread-safe) logic to determine if an instance already exists and create one if not, because Java always uses "lazy initialization". -- DougPardee 12-Jun-03

The additional version of the getThreadSafeInstance method included above shows a way to ensure creation of a single instance with minimal synchronization. This helps in situations where the instance should not be created until it is explicitely requested (although the article above about double checked locking casts some doubt on its effectiveness) -- Grandin Hammell 22-Jul-04

----- Revision r13 - 14 Feb 2007 - 10:38:26 - Main.puff