Sobes.tech
Middle — Middle+

How can a thread-safe singleton be implemented using enum without synchronization?

sobes.tech AI

Answer from AI

In Java, a thread-safe singleton can be implemented using an enum without additional synchronization, since Java guarantees that each enum element is created only once and in a thread-safe manner.

Advantages of this approach:

  • Guaranteed uniqueness of the instance.
  • Protection against serialization and reflection.
  • Simplicity of implementation.

Example implementation:

public enum Singleton {
    INSTANCE;

    public void someMethod() {
        // singleton logic
    }
}

Usage:

Singleton.INSTANCE.someMethod();

Thus, enum provides lazy and thread-safe singleton initialization without the need to use synchronized or other synchronization mechanisms.