Q74: How do you implement a Thread-Safe Singleton using Double-Checked Locking or Bill Pugh Helper?
- Double-Checked Locking: Checks instance nullity twice with a
synchronizedblock and avolatilereference variable (to prevent instruction reordering). - Bill Pugh Singleton: Uses a static inner helper class. The instance is allocated strictly when the inner class is loaded on demand by the ClassLoader (Thread-safe, lazy, zero lock overhead).
- Enum Singleton: Best practice per Joshua Bloch (handles serialization and reflection attacks automatically).
Bill Pugh Singleton Pattern
public class Singleton {
private Singleton() {} // Private constructor
private static class Helper {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Helper.INSTANCE; // Lazy thread-safe load
}
}💡 Classloader thread safety guarantees single instance allocation on Helper class access.
Key Takeaways
- Double-Checked Locking MUST declare the instance
volatile. - Bill Pugh Static Helper provides thread-safe lazy loading without locks.
- Enum Singletons prevent reflection and serialization duplication.
Knowledge Check
Why MUST the instance reference be declared volatile in a Double-Checked Locking Singleton implementation?