Singleton - Yash-777/LearnJava GitHub Wiki
Singleton: wiki
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance.
Singleton UML Class diagram:
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
An implementation of the singleton pattern must:
-
The singleton class must provide a global access point to get the instance of the class.
private static Singleton instance = null;
-
Hide the constructor of the class. Declaring all constructors of the class to be private[ACCESS-MODIFIER]
private Singleton() { if (instance != null) { // To avoid ReflectionAPI access. throw new ReflectionException("Cannot create, please use getInstance()"); } }
Reflection can be caused to destroy singleton property of singleton class. To overcome creating of instance form private constructor throw Exception.
-
Define a public static operation (getInstance()) that returns the sole instance of the class. And ensure that only one instance of the singleton class ever exists; and
public static synchronized Singleton getInstance() { // SafeLazyInitialization, ThreadSafe if (instance == null) { instance = new Singleton(); } return instance; }
Double-checked locking should not be used (squid:S2168)
Reflection API: throw exception form the constructors.
public static Singleton reflectionAPI() throws Exception {
Singleton instance = null;
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instance = (Singleton) constructor.newInstance();
break;
}
return instance;
}
class ReflectionException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ReflectionException(String message) {
super(message);
}
}
Cloning: Cloning is a concept to create duplicate objects. Using clone we can create copy of object. Suppose, we create clone of a singleton object, then it will create a copy that is there are two instances of a singleton class, hence the class is no more singleton.
"clone" should not be overridden (squid:S2975)
@Override
protected Object clone() throws CloneNotSupportedException {
//return super.clone();
//throw new CloneNotSupportedException();
return instance;
}
Overcome Cloning issue:- To overcome this issue, override clone() method and throw an exception from clone method that is CloneNotSupportedException. Now whenever user will try to create clone of singleton object, it will throw exception and hence our class remains singleton.
Now we have stopped user to create clone of singleton class by throwing the exception, or If you don;t want to throw exception you can also return the same instance from clone method.
Serialization:- Serialization can also cause breakage of singleton property of singleton classes. Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.
To Overcome serialization issue:- We have to implement method readResolve() method. "readResolve" methods should be inheritable (squid:S2062), Visibility[ACCESS-MODIFIER] should not be private.
private static final long serialVersionUID = 42L;
protected Object readResolve() throws ObjectStreamException {
return getInstance();
}
public static void writeStream(String fileName, Object instance) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
oos.writeObject(instance);
oos.close();
}
public static Singleton readStream(String fileName) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
Singleton readObject = (Singleton) ois.readObject();
ois.close();
return readObject;
}
Enum: Enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons.
enum EnumSingleton {
INSTANCE;
public void doSomething(){
System.out.println("Instance funciton.");
}
}
Example:
public static void main(String[] args) throws Exception {
System.out.println("SafeLazyInitialization, ThreadSafe");
print("Initial Check", getInstance());
print("Cross Check", getInstance());
System.out.println("Serialization");
String fileName = "D:/objectSingleton.ser";
writeStream(fileName, getInstance());
print("Initial Check", readStream(fileName));
print("Cross Check", readStream(fileName));
System.out.println("Cloning is a concept to create duplicate objects.");
Singleton clone = (Singleton) getInstance().clone();
print("Copy Singleton", clone);
System.out.println("Enum singleton - the preferred approach");
EnumSingleton.INSTANCE.doSomething();
System.out.println("Reflection API");
print("Break Singleton", reflectionAPI());
}
public static void print(String message, Singleton obj) {
System.out.format("[M]:%14s, [H]:%d\n", message, System.identityHashCode(obj));
}
Output:
SafeLazyInitialization, ThreadSafe | SafeLazyInitialization, ThreadSafe
[M]: Initial Check, [H]:366712642 | [M]: Initial Check, [H]:366712642
[M]: Cross Check, [H]:366712642 | [M]: Cross Check, [H]:366712642
Serialization | Serialization
[M]: Initial Check, [H]:1096979270 | [M]: Initial Check, [H]:366712642
[M]: Cross Check, [H]:1078694789 | [M]: Cross Check, [H]:366712642
Cloning of objects. | Cloning of objects.
[M]:Copy Singleton, [H]:1096979270 | [M]:Copy Singleton, [H]:366712642
Reflection API | Reflection API
[M]:Break Singleton, [H]:1096979270 | Exception in thread "main" java.lang.reflect.InvocationTargetException
| Caused by: ReflectionException: Cannot create, please use getInstance()
In JDK there are many places where Singleton design pattern is used. Some of these are as follows:
- java.lang.Runtime.getRuntime() Source
public class Runtime {
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}
- java.awt.Desktop.getDesktop() Source
- When is a Singleton not a Singleton?
Singleton pattern is used for logging, drivers objects, caching and thread pool.