Singleton Implementation with Double Checked Locking in Java

-> Singleton implementation is nothing but creating the object instance only once and reusing the same instance when ever needed, instead creating a new one each time when needed.
-> In the below code instance is of lazy loading initializing type as the instance of class is declared in static variable but which is initialized only when the method getInstacne is invoked. Eager loading will be like declaring and initializing at the same time.like shown below.
private volatile static Singleton instance = new Singleton();

Double checked locking Idiom:

-> Now lets talk about Double checked locking idiom in singleton implementation. Here object is null or not will be checked twice and then object for the class will be created.
-> Why Volatile is used?: In double checked locking idiom, suppose if thread A is entered first null condition and then second null condition, then it will create an object for the class. Now suppose if thread B is entered first null condition, at the same time for thread A object is getting created (but instance creation is not completed yet) then as the null condition fails it’ll just return the same object instance which not completely initialized (half baked object), which leads to unexpected behavior of object.
So when voltaile is used, which makes the object getting published only when it is completely initialized, which avoids above problem.
-> The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. This results in Thread B failing because it is using a partially constructed version of instance.

Code:

public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

 

Few References:

http://javarevisited.blogspot.in/2014/05/double-checked-locking-on-singleton-in-java.html

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s