π Table of Contents
- What is Singleton Design Pattern?
- Why Use Singleton?
- Requirements of a Singleton Class
- Implementation Types
- Thread Safety in Singleton
- Real World Use Cases
- Comparison Table
- Advantages
- Disadvantages
- Notes & Best Practices
- Quick Test
- Conclusion
Part 2 - Why You Should Avoid Singleton Pattern in Modern Java Projects
π― Singleton Design Pattern in Java
βEnsure a class has only one instance and provide a global point of access to it.β
π 1. What is Singleton Design Pattern?
The Singleton Pattern is a creational design pattern that ensures a class is instantiated only once during the application's lifecycle and provides global access to that instance.
π 2. Why Use Singleton?
- π Consistency: All parts of the application use the same instance.
- πΎ Memory Efficient: Avoids creating multiple objects.
- π Control Access: Especially for shared resources like databases, loggers, caches, etc.
π§± 3. Basic Requirements of a Singleton Class
- Private Constructor: Prevents instantiation from outside the class.
- Static Reference: Holds the single instance of the class.
- Public Static Method: Returns the singleton instance.
βοΈ 4. Implementation Types
β A Eager Initialization
The instance is created when the class is loaded (whether you use it or not).
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}
}
β Advantages
- Thread-safe by default (because of class loading).
- Simple to implement.
β Disadvantages
- Instance is created even if not used.
- Not ideal when object creation is resource-heavy.
β B Lazy Initialization
The instance is created only when needed.
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
β Advantages
- Saves memory if instance is never needed.
β Disadvantages
- Not thread-safe. In a multithreaded environment, two threads may create different instances.
π§΅ 5. Thread Safety in Singleton
π« Problem:
Two threads might simultaneously enter the getInstance()
method and create multiple instances β breaking the singleton guarantee.
π Solutions:
β A Synchronized Method
public class ThreadSafeSingleton {
private static ThreadSafeSingleton instance;
private ThreadSafeSingleton() {}
public static synchronized ThreadSafeSingleton getInstance() {
if (instance == null) {
instance = new ThreadSafeSingleton();
}
return instance;
}
}
- β Thread-safe
- β Slower performance due to method-level lock
β B Double Checked Locking
public class DoubleCheckedSingleton {
private static volatile DoubleCheckedSingleton instance;
private DoubleCheckedSingleton() {}
public static DoubleCheckedSingleton getInstance() {
if (instance == null) {
synchronized (DoubleCheckedSingleton.class) {
if (instance == null) {
instance = new DoubleCheckedSingleton();
}
}
}
return instance;
}
}
- β Lazy loaded
- β Thread-safe
- β High performance
- π Requires
volatile
to prevent instruction reordering
β 6. Real World Use Cases
Use Case | Why Singleton? |
---|---|
JDBC Connection | Single DB connection manager to avoid new creation |
Logger Utility | Central logging system for the entire application |
Configuration | Global configuration manager instance |
Cache Manager | Central cache layer shared across app modules |
File System | Access to shared file resources |
π 7. Comparison Table
Approach | Lazy? | Thread-Safe? | Performance | Use Case |
---|---|---|---|---|
Eager Initialization | β | β | Fast | Lightweight obj |
Lazy Initialization | β | β | Poor (MT) | Simple apps |
Synchronized Method | β | β | Slow | Small-scale apps |
Double-Checked Locking | β | β | Good | Web/Server apps |
β 8. Advantages of Singleton Pattern
π Pros |
---|
Ensures a single instance across app lifecycle |
Saves memory by preventing redundant object creation |
Globally accessible instance (controlled access) |
Great for shared resources (DB, Logger, Configs) |
β 9. Disadvantages of Singleton Pattern
π Cons |
---|
Difficult to test (mocking is tricky) |
Introduces global state (violates OOP encapsulation) |
Hidden dependencies across classes |
Thread safety can be hard to ensure (if not properly done) |
π 10. Notes & Best Practices
- Always prefer
Bill Pugh Singleton
orEnum Singleton
for thread safety & performance. - Avoid excessive global access. Use dependency injection where possible.
- Singleton is an anti-pattern in some contexts (because it can hide dependencies).
- Use
volatile
with double-checked locking to ensure visibility across threads. - Prefer stateless singletons to avoid concurrency issues.
π§ͺ 11. Quick Test
public class SingletonTest {
public static void main(String[] args) {
Runnable task = () -> {
DoubleCheckedSingleton obj = DoubleCheckedSingleton.getInstance();
System.out.println(Thread.currentThread().getName() + ": " + obj.hashCode());
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start(); t2.start();
}
}
You should see the same hashCode from both threads.
β Conclusion
The Singleton Pattern is simple, powerful, and commonly used, but requires careful handling in multithreaded environments. If you're designing a service or resource that should only exist once, Singleton is your go-to pattern β just be mindful of its drawbacks and test carefully.
π Explore More Design Patterns in Java
- β οΈ Why You Should Avoid Singleton Pattern in Modern Java Projects
- π Factory Design Pattern in Java β A Complete Guide
- π§° Abstract Factory Design Pattern in Java β Complete Guide with Examples
- π§± Builder Design Pattern in Java β A Complete Guide
- π Observer Design Pattern in Java β Complete Guide
- π Iterator Design Pattern in Java β Complete Guide
- π Adapter Design Pattern in Java β A Complete Guide
More Details:
Get all articles related to system design
Hastag: SystemDesignWithZeeshanAli
Git: https://github.com/ZeeshanAli-0704/SystemDesignWithZeeshanAli
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.