Problem 1 : Multiple Singletons simultaneously loaded by different Class loaders.
Solution : Make sure that Singleton object is loaded by only one class loader peeking through code.
Problem 2 : If you serialize your class and deserialize it again, there will be multiple instances of Singleton class
Solution : If we use readResolve() method, in order to return the Singleton object read, it will make sure only one instance is returned back.
public class Singleton implements Serializable
{
// Code for singleton here
// This method is called immediately after an object of this class is deserialized.
// This method returns the singleton instance.
protected Object readResolve() {
return getInstance();
}
}
Problem 3 : Multiple Singletons arising when someone has sub classed your Singleton.
Solution : This can be avoided at compile time if you make your Constructor Private.
Problem 4 : Two instances can be created when two threads are calling the getInstance() method at the same time (At the very first time)
If one thread entered the method just after the other, you can find calling the constructor twice and returning different values.
Solution : Use synchronized method or block :
public static synchronized Singleton getInstance() {
.......
}
Optimize the code using synchronized block.
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
Problem 5 : Clone the singleton object to get another object
Object obj = Singleton.getInstance(); // Get a singleton Singleton
Singleton clone = (Singleton) obj.clone(); // Let's clone the object
Here, clone() method is provided by in the java.lang.Object class.
Solution : Add a clone() method of our own, and throw a CloneNotSupportedException
public class Singleton implements Cloneable {
// Singleton implementation here
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.