//First check - To avoid more than one instance creation of Singleton class.

if (INSTANCE == null) {

synchronized (SingletonDoublyLocked.class) {

//Second check - To avoid more than one instance creation of

//Singleton class.

if (INSTANCE == null) {

INSTANCE = new SingletonDoublyLocked();

}

}

}

returnINSTANCE;

}

}

Let’s discuss in detail about logic of Doubly Locked Singleton class>

1. if (INSTANCE == null) {

2. synchronized (SingletonDoublyLocked.class) {

3. if (INSTANCE == null) {

4. INSTANCE = new SingletonDoublyLocked();

5. }

6. }

Let's say there are two threads t1 and t2 .

Let’s say t1 enters synchronized block reaches line 3, now t2 can’t reach line3 until t1 don’t leave synchronized block. By the time t1 must be waiting at line 2 after (INSTANCE == null) returned true at line 1.

Before leaving synchronized block t1 must have instantiated INSTANCE at line 4. After t1 leaves synchronization block, t2 will enter synchronized block and (INSTANCE == null) at line4 will return false because t1 already instantiated INSTANCE.

Understanding one more important concept >

At this point of time, i guess there might be one question in your mind.

Ques. Is if (INSTANCE == null) at line 1 is really needed?

Ans. If an instance of singleton class has already been created, then avoid double checked locking.

3) Creating Enum Singleton class in java>

Singleton enum - Are best way to create Singleton

Singleton enum are also thread safe.

Steps >

declare enum.

create private constructor.

Program to create Enum Singleton class>

/*

* Singleton enum - Are best way to create Singleton

* They are also thread safe.

*/

enum SingletonEnum {

SINGLETON_INSTANCE;

/** private constructor of enum. */

private SingletonEnum(){}

}

publicclass SingletonClassEnumTest {

publicstaticvoid main(String...a){

System.out.println(SingletonEnum.SINGLETON_INSTANCE);

//Let's conduct test to ensure instance return by SingletonEnum are same