Friday, 4 April 2014

Singleton Design Pattern




public class Singleton {
     
      private static Singleton uniqueInstance;

      private Singleton() {}

      public static Singleton getInstance() {
            if (uniqueInstance == null) {
                  uniqueInstance = new Singleton();
            }
            return uniqueInstance;
      }
     
 }


If two threads are making this test at the same time, and no Singleton object exists yet, they could conceivably both get past the if (uniqueInstance==null) test — which means both threads will create a Singleton object.



public class Singleton {
     
      private static Singleton uniqueInstance;

      private Singleton() {}

      public static synchronized Singleton getInstance() {
            if (uniqueInstance == null) {
                  uniqueInstance = new Singleton();
            }
            return uniqueInstance;
      }
 }



Using the synchronized keyword blocks access to the getInstance method by any new thread once a thread is executing code inside the method; any new threads attempting to get in have to wait until the current thread is finished. Using synchronized is one easy way to enforce single-threaded execution, and in this case, it solves the problem.

A better way of doing things is to make sure that test isn’t necessary at all.

public class Singleton {
     
      private static Singleton uniqueInstance = new Singleton();
     
      private Singleton() {}

      public static Singleton getInstance() {
//          if (uniqueInstance == null) {
//                uniqueInstance = new Singleton();
//          }
            return uniqueInstance;
      }
 }


This is a better solution than synchronizing the getInstance method —there’s no possibility of creating more than one object, so there’s not going to be any conflict between threads. You’ve removed all the overhead involved with synchronizing code just by taking the object-creation code out of the getInstance method.


Here’s something to be careful of — if you’re using multiple class loaders and singleton objects, you might end up with issues. Because each class loader uses its own namespace, you might in fact end up with multiple singleton objects. So if you’re using multiple class loaders, make sure your code coordinates among them to ensure only one singleton object exists at any one time.

No comments:

Post a Comment