Singleton Design Pattern

Loading...
By technoayan
Design-PatternSingleton
Singleton Design Pattern
0 min read
LLD
Design-Pattern
Singleton

Singleton Design Pattern

Learn how the Singleton Design Pattern ensures a single instance in a Java application. This article breaks it down with real-world use cases, step-by-step code examples, and best practices.

☝️ Singleton Design Pattern in Java

The Singleton Pattern ensures a class has only one instance and provides a global access point to it.

It’s one of the most used creational design patterns in real-world projects like:

  • Logging
  • Database connections
  • Configuration managers
  • Caches

🎯 Real-World Analogy

🧠 Think of a government ID system. You only get one Aadhaar card, and it’s used across all systems. You don’t need multiple Aadhaar cards for different apps.

Same for singleton β€” one instance, used everywhere.


πŸ”§ When to Use Singleton?

  • When only one instance should exist.
  • When global access is required (but avoid overusing it like a global variable).
  • When shared resources (e.g., file system, config manager, connection pool) are involved.

πŸ”₯ Basic Singleton Implementation

β˜•JAVA
class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor stops external instantiation
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton(); // lazy initialization
        }
        return instance;
    }
}

πŸ’‘ How to Use

β˜•JAVA
Singleton obj = Singleton.getInstance();

⚠️ Problem: It's Not Thread-Safe!

If two threads call getInstance() at the same time, it can create two objects. That's not what we want.


βœ… Thread-Safe Singleton (Synchronized Method)

β˜•JAVA
class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

πŸ”» Downside

Slower due to method-level locking (even when instance is already created).


⚑ Best Practice: Double-Checked Locking

β˜•JAVA
class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) { // First check (no lock)
            synchronized (Singleton.class) {
                if (instance == null) { // Second check (with lock)
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

βœ… Why This is Better?

  • Fast after first use.
  • Safe for multi-threaded access.
  • Memory efficient (volatile avoids caching issues).

πŸ§ͺ Singleton Using Enum (Simplest & Thread-Safe)

β˜•JAVA
enum SingletonEnum {
    INSTANCE;

    public void show() {
        System.out.println("Singleton using enum");
    }
}

πŸ’‘ Usage

β˜•JAVA
SingletonEnum.INSTANCE.show();

βœ… Enum is thread-safe and prevents serialization/deserialization issues by default.


πŸ“Œ Key Points to Remember

| Feature | Implementation | | --------------- | ------------------------------- | | Lazy Loading | getInstance() method | | Thread-Safe | Synchronized or Enum | | Prevent new obj | Private constructor | | Global Access | getInstance() method | | Avoid pitfalls | Use enum or double-checked lock |


🧰 Singleton in a Real Project (Logger Utility Example)

β˜•JAVA
public class Logger {
    private static Logger logger;

    private Logger() {}

    public static Logger getInstance() {
        if (logger == null) {
            synchronized (Logger.class) {
                if (logger == null) {
                    logger = new Logger();
                }
            }
        }
        return logger;
    }

    public void log(String message) {
        System.out.println("LOG: " + message);
    }
}

πŸ§ͺ Usage in Main Class

β˜•JAVA
public class App {
    public static void main(String[] args) {
        Logger logger = Logger.getInstance();
        logger.log("App started");

        Logger logger2 = Logger.getInstance();
        logger2.log("Still same logger!");

        System.out.println(logger == logger2); // true
    }
}

βœ… Output

LOG: App started LOG: Still same logger! true

🚫 Common Mistakes

  • ❌ Not handling multithreading in getInstance().
  • ❌ Creating a new object via reflection.
  • ❌ Forgetting to make the constructor private.

πŸ›‘οΈ Protection Against Reflection

β˜•JAVA
class SafeSingleton {
    private static SafeSingleton instance;

    private SafeSingleton() {
        if (instance != null) {
            throw new RuntimeException("Use getInstance() method");
        }
    }

    public static SafeSingleton getInstance() {
        if (instance == null) {
            instance = new SafeSingleton();
        }
        return instance;
    }
}

🧠 Interview Q&A

Q: Can Singleton break with Serialization? A: Yes, unless you override readResolve() method or use Enum.

Q: What design pattern category does Singleton belong to? A: Creational.

Q: Can you create a Singleton in Spring? A: Yes! Spring Beans are singleton-scoped by default.


πŸ“š Summary

  • βœ… Use Singleton when exactly one object is needed.
  • 🧡 Use thread-safe methods in concurrent applications.
  • πŸ” Use Enum or double-check locking for best results.
  • 🚫 Avoid anti-patterns like excessive global access.

Thanks for reading!

technoayan

Author & Tech Enthusiast

"Keep learning, keep growing, and keep sharing knowledge with the world."

Rate This Post

Share your thoughts and help others discover great content

Sign in to rate this post and share your feedback

Community Rating

No ratings yet. Be the first to rate this post!

Comments (0)

Leave a Comment

No comments yet. Be the first to share your thoughts!

TechnoBlogs

by Ayan Ahmad

Exploring the world of technology through insightful articles, tutorials, and personal experiences. Join me on this journey of continuous learning and innovation.

Stay Updated

Built With

React
Next.js
Tailwind
Firebase
Powered by Coffee

Every line of code written with love and caffeine β˜•

Β© 2025 TechnoBlogsβ€’Made withbyAyan Ahmad

Open source β€’ Privacy focused β€’ Built for developersβ€’Privacy Policyβ€’Terms of Service