Sunday, August 1, 2010

Simply Singleton

Singleton Design Pattern is the among the most widely used design patterns in IT world. It addresses the problem of creating exactly one instance of a class which can be globally accessible. This instance or object of class is singleton.

Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance() method.

public class MySingleton {
private static MySingleton instance = null;
protected MySingleton() {
// Exists only to defeat instantiation.
}
public static MySingleton getInstance() {
if(instance == null) {
instance = new MySingleton();
}
return instance;
}
}

public class SingletonInstantiator {
public SingletonInstantiator() {
ClassicSingleton instance = ClassicSingleton.getInstance();
ClassicSingleton anotherInstance =
new ClassicSingleton();
...
}
}


This technique of implementing Singleton is known as lazy loading as the object is instantiated when getInstance() method is called for the first time.

Why constructor is protected?? - First thing first. Protected constructor can be called by subclasses or by other classes in the same package. So keeping the MySingleton and SingletonInstantiator in the same package allows the former class to create instance of singleton class. So what should be done? First, make the constructor of MySingleton private, but then this class can not be subclassed. Second, declare MySingleton as final. Third, put your singleton class in explicit package.

A third interesting point about ClassicSingleton: it's possible to have multiple singleton instances if classes loaded by different classloaders access a singleton. That scenario is not so far-fetched; for example, some servlet containers use distinct classloaders for each servlet, so if two servlets access a singleton, they will each have their own instance.

Fourth, if ClassicSingleton implements the java.io.Serializable interface, the class's instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

Finally, and perhaps most important, Example 1's ClassicSingleton class is not thread-safe. If two threads—we'll call them Thread 1 and Thread 2—call ClassicSingleton.getInstance() at the same time, two ClassicSingleton instances can be created if Thread 1 is preempted just after it enters the if block and control is subsequently given to Thread 2. The solution to this is to synchronize the getInstance() method in our MySingleton class or just the block where we are creating the instance to improve performance by locking the object for short time.

For more information -
Java World - Simply Singleton

No comments:

Post a Comment