🚀 30 Days of Java Interview Questions – Day 11 💡 Question: What is Singleton Design Pattern in Java? 🔹 What is Singleton? Singleton Design Pattern ensures that a class has only one instance and provides a global point of access to it. 🔹 Key Features • Only one object is created • Global access to that instance • Controlled object creation 🔹 Real World Use Cases • Logger • Database Connection • Configuration Manager • Caching 🔹 Implementation Example ```java class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } ``` 🔹 Thread-Safe Singleton (Best Practice) ```java class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } ``` ⚡ Quick Facts • Supports lazy initialization • Can be made thread-safe • Used when only one instance is required 📌 Interview Tip Singleton can break due to: • Reflection • Serialization • Cloning Always use proper handling to make it robust. Follow this series for 30 Days of Java Interview Questions. #java #javadeveloper #codinginterview #backenddeveloper #softwareengineer #programming #developers #tech
the double checked locking with volatile is the correct production approach but what a lot of people miss is why volatile is actually needed there. without it the JVM can reorder instructions so another thread might see a partially constructed object through the reference before the constructor finishes. the interview tip about reflection breaking singleton is really important because most candidates cant explain how to prevent it. the fix is throwing an exception in the private constructor if an instance already exists. also worth mentioning that enum based singleton is considered the best approach by Joshua Bloch since it handles serialization and reflection attacks automatically with zero extra code
Enum singleton is best