A
A
C"How would you implement a singleton pattern in Java? Walk through a correct implementation, explain how you would make it thread-safe, and mention common mistakes or edge cases."
A singleton prevents outside code from creating new instances directly. Making the constructor private ensures the class controls its own instantiation.
private Singleton() {}
The class stores one static instance and exposes it through a public accessor. This guarantees all callers receive the same object reference.
private static Singleton instance;
public static Singleton getInstance() { return instance; }
Eager initialization creates the instance when the class is loaded, which is simple and thread-safe. Lazy initialization delays creation until first use, which can save resources but requires extra care in concurrent code.
private static final Singleton INSTANCE = new Singleton();
In multithreaded programs, two threads may create separate instances if initialization is not synchronized correctly. Common safe approaches include synchronized accessors, double-checked locking with volatile, static inner holder, and enum singletons.
private static volatile Singleton instance;
A singleton can be broken if reflection invokes the private constructor or deserialization creates a new object. Defensive checks or using an enum-based singleton can avoid these issues.
private Object readResolve() {
return getInstance();
}