This is probably an old topic, but I still find others including myself making these mistakes, so I thought I would write about it.
Everyone should know what a singleton is, usually used when you need one instantiation of an object across the system.
The incorrect way
public class BadSingleton
{
private static BadSingleton _instance;
public static BadSingleton getInstance()
{
if(_instance==null)
{
_instance = new BadSingleton();
}
return _instance;
}
private BadSingleton()
{
//do initializations here
}
}
The double checked locking way
This came about as an optimization for early JVMs, in the modern world – this is a bad practice.
public class VeryBadSingleton
{
private static VeryBadSingleton _instance;
public static VeryBadSingleton getInstance()
{
if(_instance==null)
{
synchronized(VeryBadSingleton.class)
{
if(_instance==null)
{
_instance = new VeryBadSingleton();
}
}
}
return _instance;
}
private VeryBadSingleton()
{
//do initializations here
}
}
The correct way
public class CorrectSingleton
{
private static CorrectSingleton _instance;
public synchronized static CorrectSingleton getInstance()
{
if(_instance==null)
{
_instance = new CorrectSingleton();
}
return _instance;
}
private CorrectSingleton()
{
//do initializations here
}
}
