Thread-Safe Singleton in Java
Ensuring thread safety in Singleton implementation is crucial in multi-threaded environments. A common approach is to synchronize the getInstance() method. However, this can lead to performance issues. A better alternative is using double-checked locking, which only synchronizes the code block responsible for instance creation.
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;
}
}
Bill Pugh Singleton Implementation
The Bill Pugh approach to Singleton implementation uses a static inner class. This method leverages the classloading mechanism to ensure thread safety without the need for synchronization.
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}