Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 48

Singleton Pattern in Java

In this lesson: Create a singleton class in Java — eager, lazy and thread-safe versions — with dry run and output. In Hindi & English.

What is the Singleton pattern

The Singleton pattern makes sure a class has only one object for the entire program, and gives one clear way to access it. It is a classic design pattern used when exactly one shared instance makes sense — like a single database connection or a settings manager.

💡 Singleton = one object for the whole program, reached through a shared getInstance() method.

Why use it

  • One shared resource — a single database connection, cache or logger.
  • Consistent state — everyone uses the same object, so data stays in sync.
  • Controlled access — creation happens in one place you control.

It fits any case where making several objects would be wasteful or wrong.

The Java program

class Database {
    private static Database instance;   // the single object

    private Database() {                // private constructor
        System.out.println("Database created");
    }

    public static Database getInstance() {
        if (instance == null) {         // create only once
            instance = new Database();
        }
        return instance;                // always the same object
    }
}

public class Main {
    public static void main(String[] args) {
        Database db1 = Database.getInstance();
        Database db2 = Database.getInstance();
        System.out.println(db1 == db2);  // same object?
    }
}
Database created
true

Notice "Database created" prints only once, and db1 == db2 is true — both variables point to the very same object.

Dry run

Dry Run — Singleton: only ONE object is created
StepCallinstance == null?What happens
1getInstance() (db1)yes (first time)create new Database, store in instance
2getInstance() (db2)no (already exists)return the same old instance
db1 and db2 are the same object → db1 == db2 is true
💡 Understand it this way

The first getInstance() finds instance is null, so it creates the object. Every later call finds it already exists and returns the same one — so only one object ever exists.

The three key parts

  1. Private static field — holds the single instance.
  2. Private constructor — blocks others from using new.
  3. Public static getInstance() — creates it once, returns it always.

Together these three guarantee exactly one object, accessed the same way everywhere.

Thread safety note

The simple version above is not thread-safe: two threads calling getInstance() at the same time could both see instance == null and create two objects. For multithreaded code, make getInstance() synchronized, use an eager instance, or use an enum singleton.

Common mistakes

  • Public constructor. Make it private, or others can create more objects.
  • Forgetting the null check. Without it, a new object is made every call.
  • Ignoring thread safety. Add synchronization for multithreaded use.
  • Overusing Singletons. Too much global state makes code hard to test.

Summary

  • The Singleton pattern allows only one object of a class.
  • Use a private constructor, a static instance, and getInstance().
  • getInstance() creates the object once and returns it every time.
  • It suits shared resources like a connection or configuration.
  • The basic version needs extra care to be thread-safe.

Next, revise objects in classes and objects, or the static keyword it relies on.

Frequently Asked Questions

What is the Singleton pattern?
The Singleton pattern ensures a class has only one object (instance) for the whole program, with a single point of access to it. It is used when exactly one shared object makes sense, like a database connection or a configuration manager.
How do I make a Singleton in Java?
Make the constructor private (so no one else can create objects), keep a static reference to the single instance, and provide a static getInstance() method that creates it once and returns the same object every time.
Why is the constructor private in a Singleton?
A private constructor stops other code from creating new objects with new. This forces everyone to use getInstance(), which returns the one shared instance, guaranteeing only a single object exists.
When should I use the Singleton pattern?
Use it when the program needs exactly one shared object, such as a logging service, configuration, cache, or a single database connection. Avoid overusing it, as global state can make testing harder.
Is the basic Singleton thread-safe?
The simple version is not thread-safe — two threads could create two instances at once. For multithreaded programs, use synchronization, an eager instance, or an enum singleton to make it safe.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicPalindrome Number Your progress: 48 / 61 (79%) · Lesson 49 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free