Q: Explain the Singleton design pattern in Java and provide a thread-safe implementation.
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for managing shared resources like a database connection or a logger. A thread-safe implementation is crucial in multi-threaded environments to prevent multiple threads from creating separate instances simultaneously. The example below uses the "double-checked locking" and `volatile` keyword for efficiency and thread-safety.
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;
}
public void showMessage() {
System.out.println("Hello from Singleton!");
}
}