Wednesday, 28 August 2013

Singleton Design Pattern in Java

Singleton Design Pattern

Singleton Design Pattern means able to create only one object of the class. When you want to restrict some class from being created multiple objects, this design pattern is being used.

First step of creating the class singleton is to make it's constructor private so other class can't call it anytime and create and object of it.

Then create a static method "getInstance" which will return the object of the same class . Here its SingletonExampleClass . This method (getInstance) is created static , because this class has private constructor so we won't have it's object with us to access this class first time.

Synchronized block is used stop multiple threads to access the instantiation code block at the same time, else it will be able to create multiple objects.

now assume that two thread are there T1 and T2. Not Thread T1 access this method first and acquire the lock. While Thread T1 was accessing the code inside Synchronized block, second thread T2 enters and try to access the same synchronized block, but as T1 also has lock , T2 went to waiting state. When T1 complete the execution , T2 acquire the lock, and it will be able to create the new instance once again. So here is the violation of the condition. To avoid this, we provide if conditions to check if and only if the instance is null then and then only it will go for new instance else it will return the already initialized object.

Following Books are good to refer :

public class SingletonExampleClass {
 static SingletonExampleClass instance;

 private SingletonExampleClass() {
 }

 public static SingletonExampleClass getInstance() {
  if (instance == null) {
   synchronized (SingletonExampleClass.class) {
    if (instance == null)
     instance = new SingletonExampleClass(); // 3
   }
  }
  return instance;
 }
}


Why second if statement in Singleton pattern?
Ans :
Step 1

Step -2


Step 3