Saturday, June 27, 2015

Why do we double check for null instance in Singleton lazy initialization

The algorithm for getting a singleton object of a class by using double checking  for null instances as follows

  1.  public class SigletonTest {
  2.  private static volatile SigletonTest instance = null;
  3.           // private constructor
  4.         private SigletonTest() {
  5.         }
  6.          public static SigletonTest getInstance() {
  7.             if (instance == null) {
  8.                 synchronized (SigletonTest.class) {
  9.                     // Double check
  10.                     if (instance == null) {
  11.                         instance = new SigletonTest();
  12.                     }
  13.                 }
  14.             }
  15.             return instance;
  16.         }
  17.   }

But The question is why the  instance is null checked twice in line no 7 and line no 10.It  seems it is sufficient to check  the instance as null once after synchronization block.The code as follows

public class SigletonTest {
        private static volatile SigletonTest instance = null;

        private SigletonTest() {
        }
         public static SigletonTest getInstance() {
                synchronized (SigletonTest.class) {
                    // single check
                    if (instance == null) {
                        instance = new SigletonTest();
                    }
                }
            return instance;
        }
  }

But In case of the above code ,however, the first call to getInstance() will create the object and all the  threads trying to access it during that time need to be synchronized; after that all calls just get a reference to the member variable. Since synchronizing a method could in some extreme cases decrease performance . The overhead of acquiring and releasing a lock every time this method is called seems unnecessary. Once the initialization has been completed, acquiring and releasing the locks would appear unnecessary.

So the first version is more efficient than second one.

No comments:

Post a Comment