Singleton Pattern in Java: Using Enums for Thread Safety

Post3 of Sharing a learning from Effective Java Item 3: Enforce the Singleton Property A Singleton should guarantee only one instance — even in the presence of serialization, reflection, and multithreading. Common (but fragile) approach: public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } } Best approach (recommended by Effective Java): public enum Singleton { INSTANCE; } Why enum-based singleton? • Thread-safe by default • Prevents reflection attacks • Safe against serialization issues • Simple and clean Key takeaway: If you need a true Singleton in Java, use an enum unless you have a strong reason not to. 📖 Effective Java — Joshua Bloch #Java #EffectiveJava #BackendEngineering #CleanCode #SoftwareEngineering #DesignPatterns #JavaTips #ProductEngineering

To view or add a comment, sign in

Explore content categories