The Singleton pattern is a design pattern used to restrict the number of instances of a class to one. In a multi-threaded environment, it's important to ensure that the Singleton class is thread-safe so that only one instance is created. One way to achieve thread-safety in Singleton class is by using the double-checked locking mechanism in Java.
The key idea is to check if an instance of the Singleton class exists, create one if it doesn't, and return the instance. The double-checked locking mechanism checks whether an instance has been created before acquiring the lock. This allows multiple threads to access the check simultaneously, without having to acquire the lock, and increases performance.
Here is an implementation of the thread-safe Singleton pattern using 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;
}
}
The volatile
keyword ensures that all threads see the latest value of the instance variable, and the synchronized block which ensures mutual exclusion while creating the instance.
In conclusion, the double-checked locking mechanism is a useful technique for implementing a thread-safe Singleton pattern. It allows efficient shared access to the singleton object while maintaining thread-safety.
Reference:
Java Concurrency in Practice by Brian Goetz et. al. Chapter 16
For more information, please refer to https://www.baeldung.com/java-singleton-double-checked-locking