Double Lock check in Singleton is generally written as :
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null) //2
instance = new Singleton(); //3
}
}
return instance; //4
}
In the code above, suppose ten threads are calling this method, all of them crossed the first if condition, then one thread enters into the synchronized block and creates the instances. Remaining 9 thread would come one by one even if the instance is created they need to wait and come in sequence through the synchronized block. I want that as soon as any of the threads creates the Singleton instance all the other threads should not wait. Tell me if there is some solution for this?
I don’t think there’s a solution if you insist on using lazy instantiation.You could just create your singleton object when you declare theinstancevariable:Thanks to the comment by eSniff (and the comment by yair to set me right about eSniff’s comment), here’s the method posted in Wikipedia for a thread-safe and lazy method: