How to create thread-safe Singleton?
Creating a thread-safe singleton in Java ensures that only one instance of the singleton object is created and shared among multiple threads in a multi-threaded environment. There are several approaches to achieve thread safety in singleton design pattern, such as using eager initialization, lazy initialization with synchronized block, double-checked locking, and enum.

Table of Contents
Explanation
1. Eager Initialization: In this approach, the singleton instance is created at the time of class loading. It ensures thread safety because the JVM guarantees that class loading is inherently thread-safe.
2. Lazy Initialization with Synchronized Block: In this approach, the singleton instance is created lazily (i.e., when it is first requested). Synchronization is used to ensure that only one instance is created in a multi-threaded environment.
3. Double-Checked Locking: This approach combines lazy initialization with synchronization to minimize synchronization overhead by using double-checked locking.
4. Enum: Using enum is a simpler and safer way to implement a thread-safe singleton because enums inherently provide thread safety and serialization safety.
Java Example using Lazy Initialization with Synchronized Block:
java
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
// Private constructor to prevent instantiation
private ThreadSafeSingleton() {}
// Lazy initialization with synchronized block
public static synchronized ThreadSafeSingleton getInstance() {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
return instance;
}
}
In this example, ThreadSafeSingleton class implements lazy initialization with a synchronized block. The getInstance() method is synchronized to ensure that only one thread can create the singleton instance at a time. If the instance variable is null, it creates a new instance of ThreadSafeSingleton. However, this approach introduces synchronization overhead, which can impact performance in high-concurrency scenarios.