Double Check Locking- pattern

Double check locking pattern is used for double checking the condition before acquiring a lock on an object. This helps reducing unneccary locks.

To understand lets take a simple example of creating a singleton object.

public static MySingleton getInstance()
{
if(null==mysingleton)
mysingleton=new MySingleton();
return mysingleton;
}

The challenge with above code is that it is not threadsafe. So we might end up creating multiple objects of MySingleton in case of multithreaded environment. So we will add synchronization.

public static synchronized MySingleton getInstance()
{
if(null==mysingleton)
mysingleton=new MySingleton();
return mysingleton;
}

Though we have saved our code from multi threading, we have added additional load of synchronization, i.e. each thread will have to wait for previous thread to finish processing of this method before entering into it. The actual error case will occur only for first time, i.e. when mysingleton object is null, we would like to stop other threads to execute the block. So to optimiza the code, we will use a technique called double locking.

public static synchronized MySingleton getInstance()
{
if(null==mysingleton)
{
synchronized(MySingleton.class) {
if(null==mysingleton)
mysingleton=new MySingleton();
}
}
return mysingleton;
}

You can see we are applying synchronized block only when we are sure that we are in a case we want to stop multiple threads from going ahead, rather than blocking threads all the time.

http://en.wikipedia.org/wiki/Double-checked_locking