Thursday 21 March 2019

                                                        singleton design pattern in java?



Java Singleton
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, drivers objects, caching and thread pool.
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.
Java Singleton Pattern
To implement a Singleton pattern, we have different approaches but all of them have the 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.
If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc. We should avoid the instantiation until unless client calls the getInstance method. Also, this method doesn’t provide any options for exception handling.
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton instance = new EagerInitializedSingleton();
//private constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public String printName(String s1)
{
return s1;
}
public static EagerInitializedSingleton getInstance(){
return instance;
}
public static void main(String args[])
{
EagerInitializedSingleton eis=EagerInitializedSingleton.getInstance();
String s1=eis.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:-------------
E:\>javac EagerInitializedSingleton.java
E:\>java EagerInitializedSingleton
Govind Ballabh Khan
=========================================================================================================================================================================================
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.
Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create a Singleton class that supports lazy initialization.
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
public String printName(String s1)
{
return s1;
}
//static block initialization for exception handling
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in creating singleton instance");
}
}
public static StaticBlockSingleton getInstance(){
return instance;
}
public static void main(String args[])
{
StaticBlockSingleton sbs=StaticBlockSingleton .getInstance();
String s1=sbs.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:-------------
E:\>javac StaticBlockSingleton.java
E:\>java StaticBlockSingleton
Govind Ballabh Khan
=======================================================================================================================================================================================
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.
The above implementation works fine in case of the single-threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if condition at the same time. It will destroy the singleton pattern and both threads will get the different instances of the singleton class. In next section, we will see different ways to create a thread-safe singleton class.
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public String printName(String s1)
{
return s1;
}
public static LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
public static void main(String args[])
{
LazyInitializedSingleton lis=LazyInitializedSingleton .getInstance();
String s1=lis.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:--------------------------------------
E:\>javac LazyInitializedSingleton.java
E:\>java LazyInitializedSingleton
Govind Ballabh Khan
============================================================================================================================================================================================
Thread Safe Singleton
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.
Above implementation works fine and provides thread-safety but it reduces the performance because of the cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization).
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public String printName(String s1)
{
return s1;
}

public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
public static void main(String args[])
{
ThreadSafeSingleton tss=ThreadSafeSingleton .getInstance();
String s1=tss.printName("Govind Ballabh Khan");
System.out.println(s1);
}
}
o/p:----------------------------------------------------------------
C:\Users\govin>e:
E:\>javac ThreadSafeSingleton.java
E:\>java ThreadSafeSingleton
Govind Ballabh Khan

No comments:

Post a Comment