Singleton is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category. Here we will learn about Singleton design pattern principles, different ways to implement Singleton and some of the best practices for its usage.
Singleton Pattern
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, driver’s objects, and caching and thread pool.
Singleton design pattern
is also used in other design patterns like Abstract
Factory, Builder, Prototype, Façade etc. Singleton design
pattern is used in core java classes also, for example java.lang.Runtime
, java.awt.Desktop
.
Java Singleton Pattern
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.
Different approaches of Singleton pattern implementation and design concerns with the
implementation.
1.
Eager initialization
2.
Static block initialization
3.
Lazy Initialization
4.
Thread Safe Singleton
5.
Bill Pugh Singleton Implementation
6.
Using Reflection to destroy Singleton Pattern
7.
Enum Singleton
8.
Serialization and Singleton
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.
Here is the implementation of static initialization singleton
class.
EagerInitializedSingleton.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package com.journaldev.singleton;
public class EagerInitializedSingleton {
private static final EagerInitializedSingleton
instance = new EagerInitializedSingleton();
//private
constructor to avoid client applications to use constructor
private EagerInitializedSingleton(){}
public static EagerInitializedSingleton getInstance(){
return instance;
}
}
|
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.
StaticBlockSingleton.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.journaldev.singleton;
public class StaticBlockSingleton {
private static StaticBlockSingleton instance;
private StaticBlockSingleton(){}
//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;
}
}
|
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 Singleton
class that supports lazy initialization.
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.
LazyInitializedSingleton.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package com.journaldev.singleton;
public class LazyInitializedSingleton {
private static LazyInitializedSingleton instance;
private LazyInitializedSingleton(){}
public static LazyInitializedSingleton getInstance(){
if(instance
== null){
instance
= new LazyInitializedSingleton();
}
return instance;
}
}
|
The above implementation works fine incase of single threaded
environment but when it comes to multithreaded systems, it can cause issues if
multiple threads are inside the if loop at the same time. It will destroy the
singleton pattern and both threads will get the different instances of
singleton class. In next section, we will see different ways to create a thread-safe singleton
class.
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.
ThreadSafeSingleton.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
package com.journaldev.singleton;
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton(){}
public static synchronized ThreadSafeSingleton getInstance(){
if(instance
== null){
instance
= new ThreadSafeSingleton();
}
return instance;
}
}
|
Bill Pugh Singleton Implementation
Prior
to Java 5, java memory model had a lot of issues and above approaches used to
fail in certain scenarios where too many threads try to get the instance of the
Singleton class simultaneously. So Bill Pugh came up with a different approach
to create the Singleton class using an inner static helper class. The Bill Pugh Singleton
implementation goes like this;
BillPughSingleton.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package com.journaldev.singleton;
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton
INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
|