Sobes.tech
Junior — Middle

Does implementing Singleton guarantee safety when working in a multithreaded environment?

sobes.tech AI

Answer from AI

The default implementation of the Singleton pattern does not guarantee thread safety. If multiple threads attempt to create an instance simultaneously, it may result in multiple objects being created.

Various approaches are used to ensure thread safety:

  • Using the synchronized keyword when creating the instance.
  • Eager initialization of the instance at class load time.
  • Using a static nested class (Initialization-on-demand holder idiom).
  • Using enum to implement Singleton (in Java).

Example of a thread-safe Singleton using synchronized:

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

However, this approach can reduce performance due to synchronization. A more efficient method is double-checked locking with volatile.