What is singleton?
Singleton
Steps to make singleton
private Constructor
static getInstance method
synchronized
override clone() method
disadvantage of Singleton
it carries state of object
it prevents dependency injection and cannot be unit tested
https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
The singleton class must provide a global access point to get the instance of the class.
Singleton pattern is used for logging thread pool, drivers objects, caching and
Singleton design pattern is also used in other design patterns like Abstract Factory Builder, Prototype, Facade etc.
Singleton design pattern is used in core java classes also, for example
java.lang.Runtime,java.awt.Desktop
To implement Singleton pattern, we have different approaches but all of them have following common concepts.
Private constructor to restrict instantiation of the class from other classes.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
Eager initialization
In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.
Static block initialization
Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.
not thread safe
Thread Safe Singleton
The snippetsynchronized(X.class)
uses the class instance as a monitor. As there is only one class instance (the object representing the class metadata at runtime) one thread can be in this block.
Withsynchronized(this)
the block is guarded by the instance. For every instance only one thread may enter the block.
synchronized(X.class)
is used to make sure that there is exactly one Thread in the block. synchronized(this)
ensures that there is exactly one thread per instance. If this makes the actual code in the block thread-safe depends on the implementation. If mutate only state of the instancesynchronized(this)
is enough.
Bill Pugh Singleton Implementation
Notice the private inner static class that contains the instance of the singleton class. When the singleton class is loaded,SingletonHelper
class is not loaded into memory and only when someone calls the _getInstance _method, this class gets loaded and creates the Singleton class instance.
This is the most widely used approach for Singleton class as it doesn’t require synchronization.
Serialization and Singleton
The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class.
So it destroys the singleton pattern, to overcome this scenario all we need to do it provide the implementation of
readResolve()
method.
Enum Singleton(best method of making singletons in Java.)
Since Java Enum values are globally accessible, so is the singleton. The drawback is that the enum type is somewhat inflexible; for example, it does not allow lazy initialization.
eg0:
eg1:
Problems with enum as singleton
enums do not support lazy loading
Though it's very very rare but if you changed your mind and now want to convert your singleton to multi-ton, enum would not allow this.
Steps to make singleton
private Constructor
static getInstance method
synchronized
override clone() method
Disadvantage of Singleton
it carries state of object
it prevents dependency injection and cannot be unit tested
eg:
https://stackoverflow.com/questions/30671534/why-enum-singleton-are-serialization-safe
Why Enum singleton are serialization safe?
Serialization treats enums specially. Basically, it stores only a reference to its class and the name of the constant. Upon deserialization, this information is used to lookup the existing runtime object of the enum type.
Thus, if you deserialize the enum constant within the same runtime, you will get the same runtime instance you have serialized.
However, when deserializing in another JVM, the hashcode might be different. But having the same hashcode is not a required criteria for singletons. The important point is to never have another instance of the class and this is guaranteed as the serialization implementation will never create an instance of an enum type but only lookup existing constants.
Last updated
Was this helpful?