HuntExams Academy logo
JavaAdvanced#design-patterns

What is the Singleton pattern? How to implement it thread-safely?

Answer

Ensures only one instance per JVM. Thread-safe options: eager initialization, double-checked locking with volatile, or the enum singleton (recommended by Joshua Bloch — serialization-safe and reflection-safe).

Example

public enum Singleton {
  INSTANCE;
  public void doWork() { System.out.println("working"); }
}
Singleton.INSTANCE.doWork();

Related Interview Questions

1
JavaIntermediate#design-patterns#spring

What is dependency injection?

Open
2
JavaBeginner#exceptions

What is the difference between throw and throws?

Open
3
JavaIntermediate#exceptions

Explain try-with-resources.

Open