Singleton Design Pattern discussion

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-09

Problem Statement


In large-scale applications, there are certain components that should have only one instance throughout the application's lifecycle.


Examples include:


•A single database connection pool
•A single configuration manager
•A single logging service
•A single thread pool manager


To ensure that only one instance of such a class is created and shared globally, we use the Singleton Design Pattern.


🎯 Problem Statement


Design and implement a Singleton class that ensures:


1.Only one instance of the class can exist in the entire application.
2.The instance can be accessed globally.
3.The class is thread-safe (for concurrent environments).
4.The instance is lazy-initialized (created only when first needed).


Demonstrate this by designing a Logger or ConfigurationManager class using the Singleton pattern.


✅ Functional Requirements


Single Instance Guarantee

•The system must prevent multiple instantiations of the class, even when accessed by multiple threads.

Global Access Point

•Provide a static method like getInstance() to access the object globally.

Lazy Initialization

•The object should be created only when it is first requested, not at application startup.

Thread Safety

•The implementation must handle multi-threaded access correctly.

Demonstration

•Show usage of Singleton in a small example like a Logger that prints consistent log IDs from all threads.


⚙️ Non-Functional Requirements


Aspect with Description


Thread Safety

Must handle concurrent getInstance() calls safely


Performance

Should not introduce unnecessary synchronization overhead


Testability

Should be testable (though difficult in some singleton implementations)


Extensibility

Should allow lazy loading or double-checked locking pattern for optimization


🧱 Core Class: Example — Logger (Singleton)

1 2public class Logger { 3 private static volatile Logger instance; 4 private static int logCount = 0; 5 6 // Private constructor prevents instantiation from outside 7 private Logger() {} 8 9 public static Logger getInstance() { 10 if (instance == null) { // Lazy initialization 11 synchronized (Logger.class) { // Thread safety 12 if (instance == null) { 13 instance = new Logger(); 14 } 15 } 16 } 17 return instance; 18 } 19 20 public void log(String message) { 21 logCount++; 22 System.out.println("[Log " + logCount + "]: " + message); 23 } 24}


💬 Example Usage

1 2public class Main { 3 public static void main(String[] args) { 4 Logger logger1 = Logger.getInstance(); 5 Logger logger2 = Logger.getInstance(); 6 7 logger1.log("Starting the application..."); 8 logger2.log("Application running..."); 9 10 System.out.println(logger1 == logger2); // true 11 } 12}


🧠 Discussion Points (for Interview)


Why Singleton?

•Ensures controlled resource usage (e.g., one database connection pool or one configuration object).

Problems it Solves

•Prevents multiple instances in distributed or multi-threaded environments.
•Provides a single source of truth for shared data.

Common Pitfalls

•Not thread-safe if not synchronized.
•Can lead to tight coupling and hidden dependencies.
•Difficult to mock/test in unit testing.

Variants

•Eager Initialization Singleton
•Lazy Initialization Singleton
•Thread-safe Double-Checked Locking
•Enum-based Singleton (in Java)
•Bill Pugh Inner Class Singleton


💬 Interview Prompt (Final Form)

Design a Singleton class (e.g., Logger, ConfigurationManager, or DatabaseConnectionPool).
Ensure that the implementation supports lazy initialization, is thread-safe, and guarantees that only one instance is ever created.
Explain how your design prevents race conditions and how you would extend or test it.


Solution

Comments