Skip to main content

Singleton: pattern or anti-pattern?

Many people consider the singleton an anti-pattern. Many others think it's part of the creational patterns family. I don't care about its definition and I think a singleton can be useful sometimes in the real world! Singleton design pattern is used when you want to have only one instance of a given class. Let's see some Java implementations:

Eagerly Initialized Singleton


public class Singleton {

   private static final Singleton INSTANCE = new Singleton();

   private Singleton() {}

   public static Singleton getInstance(){
       return INSTANCE;
   }
}

Lazily Initialized Singleton


public class Singleton {

   private static Singleton INSTANCE = null;

   private Singleton() {}

   public static Singleton getInstance() {

       if (INSTANCE == null) {
           synchronized (Singleton.class) {
               if (INSTANCE == null) {
                   INSTANCE = new Singleton();
               }
           }
       }
       return INSTANCE;
   }
}

Lazily Initialized Double-Checked Locking Singleton


public class LazyDoubleCheckedLockingSingleton {

   private static volatile LazyDoubleCheckedLockingSingleton instance;

   /** private constructor to prevent others from instantiating this class */
   private LazyDoubleCheckedLockingSingleton() {}

   /** Lazily initialize the singleton in a synchronized block */
   public static LazyDoubleCheckedLockingSingleton getInstance() {
       if(instance == null) {
           synchronized (LazyDoubleCheckedLockingSingleton.class) {
               // double-check
               if(instance == null) {
                   instance = new LazyDoubleCheckedLockingSingleton();
               }
           }
       }
       return instance;
   }
}

Lazily Initialized Inner Class Singleton (Bill Pugh singleton)


public class LazyDoubleCheckedLockingSingleton {

   private static volatile LazyDoubleCheckedLockingSingleton instance;

   /** private constructor to prevent others from instantiating this class */
   private LazyDoubleCheckedLockingSingleton() {}

   /** Lazily initialize the singleton in a synchronized block */
   public static LazyDoubleCheckedLockingSingleton getInstance() {
       if(instance == null) {
           synchronized (LazyDoubleCheckedLockingSingleton.class) {
               // double-check
               if(instance == null) {
                   instance = new LazyDoubleCheckedLockingSingleton();
               }
           }
       }
       return instance;
   }
}

Resources