Singleton Pattern In Java
January 22nd, 2009
Singleton pattern is probably one of most popular widely used patterns that I have seen. It’s implemented to create an access restriction to a specific resource like: printer, network, pooling, memory, logging.
Here is a simple and correct implementation:
public class Singleton implements Serializable{
private static Singleton _INSTANCE = null;
static{
_INSTANCE = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return _INSTANCE;
}
}
Lets look at one by one.
private static Singleton _INSTANCE keeps reference of the instance
static block this will prevent multi-thread initialization
readResolve() to make sure a new instance is not created by deserialization process
Beware that double locking solution will not work:
class Singleton {
private static Singleton singleton = null;
public static Singleton getSingleton() {
if (singleton == null){
synchronized(this) {
if (singleton == null)
singleton = new Singleton ();
}
}
return singleton ;
}
}
Please read the article why.