This article is part of Reference 1 and Reference 2. I just organize them in my own way.
GOF definition
Ensure a class only has one instance, and provide a global point of access to it.
Common use
The Abstract Factory, Builder, and Prototype patterns can use Singletons in their implementation.
Facade objects are often singletons because only one Facade object is required.
State objects are often singletons.
-
Singletons are often preferred to global variables because:
They do not pollute the global namespace (or, in languages with namespaces, their containing namespace) with unnecessary variables.
They permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.
Java implementation
Eager initialization
If the program will always need an instance, or if the cost of creating the instance is not too large in terms of time/resources, the programmer can switch to eager initialization.
public class Singleton{
private static final Singleton INSTANCE = new Singleton();
// private constructor avoid client to use
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
-
This method has a number of advantages:
The static initializer is run when the class is initialized, after class loading but before the class is used by any thread. (thread-safe)
There is no need to synchronize the getInstance() method, meaning all threads will see the same instance and no (expensive) locking is required.
The final keyword means that the instance cannot be redefined, ensuring that one (and only one) instance ever exists.
-
weekness
- Eager initialization creates the instance even before it's being used.
Static block initialization
Some authors refer to a similar solution allowing some pre-processing (e.g. for error-checking).
public class Singleton {
private static final Singleton instance;
static {
try {
instance = new Singleton();
} catch (Exception e) {
throw new RuntimeException("error", e);
}
}
public static Singleton getInstance() {
return instance;
}
private Singleton() {}
}
Lazy initialization
no thread-safe
public class Singleton{
private static Singleton instance = null;
private SingletonDemo() { }
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
simple thread-safe
public class Singleton{
private static Singleton instance = null;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances. To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.
double-checked locking
public class Singleton{
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null ) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
Initialization-on-demand holder idiom
Prior to Java 5, java memory model had a lot of issues and double-checked locking approach 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 a inner static helper class
public class Singleton {
private Singleton() { }
private static class SingletonHelpder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
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 approach has both advantages, thread-safe
and lazy load
.
Using Reflection to destroy Singleton Pattern
Reflection can be used to destroy all the above singleton implementation approaches. Let’s see this with an example class.
import java.lang.reflect.Constructor;
public class ReflectionSingletonTest {
public static void main(String[] args) {
Singleton instanceOne = Singleton.getInstance();
Singleton instanceTwo = null;
try {
Constructor[] constructors = Singleton.class.getDeclaredConstructors();
for (Constructor constructor : constructors) {
// Below code will destroy the singleton pattern
constructor.setAccessible(true);
instanceTwo = (Singleton)constructor.newInstance();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(instanceOne.hashCode());
System.out.println(instanceTwo.hashCode());
}
}
When you run the above test class, you will notice that hashCode of both the instances are not same that destroys the singleton pattern. Reflection is very powerful and used in a lot of frameworks like Spring and Hibernate.
The enum way
To overcome this situation with Reflection, Joshua Bloch suggests the use of Enum to implement Singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program. 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.
public enum Singleton {
INSTANCE;
public static void doSomething(){
//do something
}
}