Singleton pattern
restricts the instantiation of a class and ensures that only one instance of
the class exists in the java virtual machine. The single class must provide a
global access point to get the instance of the class. Singleton pattern is used for logging, driver
object, and caching and thread pool. Singleton pattern is also used in other
design pattern like as Abstract Factory and Facade.
In Singleton, we have different approaches but
all of them have same common concept.
- Private constructor to restrict instantiation of the class from other classes.
- Private static variable of the same class that is 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.
Different approaches of singleton pattern:
- Static block initialization
- Lazy initialization
- Thread Safe Singleton
- Serialization and singletone.
In Static block initialization ,the instance of
Singleton class is created at the time of class loading and that instance of class is created in the
static block that provide option for exception handling.
Example :
This
is not best practice to use, so in further section we will see how to create
singleton class that supports lazy initialization.
In Lazy initialization, method to implement Singleton pattern
create a instance in global access method, see in below example:
In above the example is suitable for single threaded
environment ,but when it comes to multi-threaded environment , it can cause
issues if multiple threads are inside the if loop at the same time, it will be
destroy the singleton pattern and both thread will get different instance of
the singleton class. In next example. We will see different ways to create at
thread-safe singleton class.
In thread Safe Singleton, this is easier way to create a thread safe
singleton class is to make the global
access method Synchronized so that
only one thread can be execute this method at a time, See in below example.
Above the example is thread- safe but
it reduce the performance because of synchronized method, So that ,if the
synchronized block is used inside the if condition with additional check to
ensure that only one instance of the singleton class create.
public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance
== null){
instance
= new ThreadSafeSingleton();
}
}
}
return instance;
}
In Serialization and
Singleton, sometime in distributed
system, we needed to implement serializable interface in Single class so that
we can store it’s state in file system and retrieve it at later point to time.Here
is a sample single class that implements serializable interface also.
1 comment:
wow good explanation .
Post a Comment