00:00

Singleton Design Pattern in Java

Last updated:

The singleton design pattern in Java ensures that a class has exactly one instance and gives the rest of the program a single, well-known way to reach it. The class hides its constructor and hands out the same object every time, typically through a static getInstance() method or an enum constant.

Some objects are expensive to build or must hold state that everyone shares: a rate cache, an ID sequence, an audit trail. If every service calls new, you pay the cost repeatedly, and worse, each copy drifts out of sync. Singleton is the simplest of the creational design patterns, and also the one most often misused, so this tutorial covers both how to write it and when not to.

1. What Is the Singleton Design Pattern?

The GoF intent is: "Ensure a class only has one instance, and provide a global point of access to it." That sentence holds two promises:

  • One instance: the class itself controls creation, so no caller can make a second object.
  • A known access point: every caller reaches the same object the same way.

In Java this works through three language features: a private constructor blocks new from outside, a static field holds the only instance, and a static method or an enum constant exposes it. "One" means one per class loader. In a normal application that is one per JVM, but not one per cluster.

2. Key Components

ComponentResponsibility
Private constructorPrevents other classes from creating instances
Static instance fieldHolds the single object, usually private static final
Static accessorgetInstance() returns that object, creating it first if the singleton is lazy
ClientAny code that calls the accessor and uses the instance

Unlike most patterns, there is no separate interface or subclass: the class plays every creational role itself. Clients never construct it; they ask for it.

3. When Is a Singleton Useful?

  • Shared, expensive state: an exchange-rate cache loaded from a bank feed should be loaded once and seen by checkout and invoicing alike.
  • Coordinating access: an order-number generator must be one object, or two copies would hand out the same number.
  • One record of events: a payment audit trail must collect events from every service into one place.

4. UML Class Diagram

The diagram shows the Basic Example. Underlined members are static.

Singleton UML class diagram CheckoutService and InvoiceService both use ExchangeRateRegistry. ExchangeRateRegistry has a private static INSTANCE field of its own type, a private constructor and a public static getInstance method. CheckoutService InvoiceService uses uses ExchangeRateRegistry - INSTANCE: ExchangeRateRegistry - rates: Map<String, BigDecimal> - ExchangeRateRegistry() + getInstance(): ExchangeRateRegistry + rate(currency): BigDecimal + update(currency, rate): void 1
Singleton: the class keeps its only instance in a private static field and returns it from a public static method; clients cannot call the private constructor.
  1. ExchangeRateRegistry has a private static field of its own type: the single instance. The arrow back to the class with multiplicity 1 shows that self-reference.
  2. The constructor is marked - (private), so the clients have no way to call it.
  3. getInstance() is + (public) and static, the only way in.
  4. Both services depend on the registry (dashed "uses" arrows) and receive the same object.

5. Step-by-Step Execution Flow

  1. The first time code touches ExchangeRateRegistry, the JVM loads and initialises the class.
  2. Initialisation runs the static field initialiser, which calls the private constructor once. The JVM runs class initialisation only once and makes other threads wait for it, so this step is thread-safe.
  3. CheckoutService calls getInstance() and gets the reference stored in INSTANCE.
  4. InvoiceService calls getInstance() and gets the same reference. No new object is created.
  5. An update made through one reference is visible through the other, because there is only one object.

The lazy holder idiom in the Practical Example uses the same JVM guarantee, but delays it until getInstance() is first called.

6. Real-World Use Cases

  • E-commerce: a shared catalogue or price cache that is loaded once at startup.
  • Payments and banking: an exchange-rate registry, or an audit trail that every payment step writes to.
  • Notifications: one rate limiter per JVM, so all senders share the same quota.
  • The JDK: Runtime.getRuntime() returns the one Runtime object of the running application, and Collections.emptyList() returns one shared immutable instance.
  • Spring Framework: beans are singleton-scoped by default, but that means one instance per application context, managed by the container. It is not the GoF Singleton: the class has a public constructor and could be created again elsewhere.

7. Problem Without the Pattern

Two services each create their own rate cache:

RatesWithoutSingleton.java
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class RatesWithoutSingleton {

    static final class ExchangeRates {
        private final Map<String, BigDecimal> rates = new HashMap<>();

        ExchangeRates() {
            System.out.println("Loading rates from the bank feed...");   // slow network call in real life
            rates.put("USD", new BigDecimal("83.20"));
        }

        BigDecimal rate(String currency) { return rates.get(currency); }

        void update(String currency, BigDecimal rate) { rates.put(currency, rate); }
    }

    public static void main(String[] args) {
        ExchangeRates checkoutRates = new ExchangeRates();   // checkout service makes its own copy
        ExchangeRates invoiceRates = new ExchangeRates();    // invoice service makes another

        checkoutRates.update("USD", new BigDecimal("83.45"));   // only one copy sees the new rate
        System.out.println("Checkout uses USD = " + checkoutRates.rate("USD"));
        System.out.println("Invoice uses USD  = " + invoiceRates.rate("USD"));
    }
}
Console
Loading rates from the bank feed...
Loading rates from the bank feed...
Checkout uses USD = 83.45
Invoice uses USD  = 83.20
  • Wasted work: the slow feed is loaded twice, once per copy.
  • Inconsistent data: checkout charges at 83.45 while invoicing still prints 83.20.
  • Nothing enforces sharing: any developer can call new again.

8. Solution Using the Pattern

Make the constructor private and let the class create and return its own single instance. Now the feed is loaded once, both services read the same map, and a third new is a compile error rather than a code-review comment.

The pattern solves the creation problem, not the concurrency problem. Because many threads share the object, its state must be thread-safe; the examples use ConcurrentHashMap, AtomicLong and CopyOnWriteArrayList for that.

9. Singleton Design Pattern in Java: Code Examples

The tabs show the three implementations worth knowing: eager, lazy holder and enum. Each file runs on Java 21 with java FileName.java.

Basic Example: Eager Exchange-Rate Registry

Problem: fix section 7 so that both services share one rate cache.

ExchangeRateRegistryDemo.java
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ExchangeRateRegistryDemo {

    static final class ExchangeRateRegistry {
        private static final ExchangeRateRegistry INSTANCE = new ExchangeRateRegistry();   // created when the class is initialised

        private final Map<String, BigDecimal> rates = new ConcurrentHashMap<>();

        private ExchangeRateRegistry() {                     // no one else can call new
            System.out.println("Loading rates from the bank feed...");
            rates.put("USD", new BigDecimal("83.20"));
        }

        static ExchangeRateRegistry getInstance() {
            return INSTANCE;
        }

        BigDecimal rate(String currency) { return rates.get(currency); }

        void update(String currency, BigDecimal rate) { rates.put(currency, rate); }
    }

    public static void main(String[] args) {
        ExchangeRateRegistry checkoutRates = ExchangeRateRegistry.getInstance();
        ExchangeRateRegistry invoiceRates = ExchangeRateRegistry.getInstance();

        checkoutRates.update("USD", new BigDecimal("83.45"));
        System.out.println("Checkout uses USD = " + checkoutRates.rate("USD"));
        System.out.println("Invoice uses USD  = " + invoiceRates.rate("USD"));
        System.out.println("Same object? " + (checkoutRates == invoiceRates));
    }
}

Important classes and methods

  • INSTANCE is created eagerly, when the class is initialised.
  • The private constructor blocks new from other classes.
  • getInstance() just returns the field, so it needs no locking.

Expected output

Console
Loading rates from the bank feed...
Checkout uses USD = 83.45
Invoice uses USD  = 83.45
Same object? true

How it runs

  1. The first getInstance() call initialises the class, which loads the rates once.
  2. The second call returns the same object.
  3. The update is visible to both services, and == confirms one object.

10. Best Practices and Common Mistakes

Best practices

  • Prefer an enum when the singleton must be serializable, or the holder idiom when you need laziness and a class.
  • If a class singleton is Serializable, add readResolve() returning INSTANCE.
  • Expose the singleton through an interface and inject it, so callers stay testable.
  • Make shared state immutable or use concurrent types. One instance means many threads touch the same fields.

Common mistakes

  • Unsynchronised lazy initialisation (if (instance == null) instance = new ...): two threads can both create an instance.
  • Double-checked locking without volatile, which can publish a half-built object.
  • Storing request data in fields of a singleton or Spring bean, which leaks data between users.
  • Overengineering: turning every service or helper into a singleton. A stateless utility needs static methods or plain dependency injection, not a singleton.

11. When to Use and When Not to Use

Use it for a resource that is truly one per process, that is costly to create, and whose callers are not managed by a container.

Avoid it in Spring Boot applications, where a @Component is already one instance per context and is easier to test. Avoid it for anything that differs per tenant, request or test, and never rely on it for cluster-wide uniqueness: five service replicas mean five instances.

12. Advantages and Disadvantages

Advantages

  • One shared instance, so state stays consistent.
  • Expensive setup runs once.
  • Lazy creation is possible with the holder idiom.
  • Simple: no extra classes or frameworks.

Disadvantages

  • Hidden dependencies: getInstance() calls do not appear in constructors.
  • Hard to test: shared state leaks between tests, and it is hard to replace.
  • Mixes two jobs (business logic and lifecycle control), against Single Responsibility.
  • Per class loader only, not per cluster.

13. Comparison with Similar Patterns

AspectSingletonStatic utility classSpring singleton beanFlyweight
InstancesExactly one per class loaderNoneOne per application contextOne per distinct shared state
Holds stateYesShould notUsually notOnly immutable shared state
Implements interfacesYesNoYesYes
Who enforces "one"The class itselfNot applicableThe containerA factory with a cache
TestabilityWeak unless injectedWeakStrongGood

Choose a static utility class for stateless helpers like Math. Choose a Spring bean whenever a container is available. Choose a Singleton for a single stateful resource outside a container, and Flyweight when you want many shared objects, one per value. A factory or abstract factory is often itself a singleton.

14. Summary

  • The singleton design pattern in Java guarantees one instance per class loader and one way to reach it.
  • Purpose: share expensive or coordinating state without duplicate copies.
  • Components: private constructor, static instance field, static accessor, clients.
  • The JVM's one-time class initialisation makes eager and holder singletons thread-safe.
  • Used for caches, ID generators, audit trails and JDK objects such as Runtime.
  • Prefer enum or the holder idiom, and keep the instance's own state thread-safe.
  • Inject it through an interface, and remember that it is not unique across a cluster.

15. Java Design Pattern Interview Questions and Answers

Q1. Why does double-checked locking need the volatile keyword?

instance = new Registry() is not one step: the JVM may publish the reference before the constructor's writes are visible. Without volatile, a second thread can pass the unsynchronised first check and use a half-initialised object. Since Java 5 (JSR-133), volatile creates a happens-before edge that prevents this.

private static volatile Registry instance;

static Registry getInstance() {
    Registry local = instance;
    if (local == null) {
        synchronized (Registry.class) {
            local = instance;
            if (local == null) {
                instance = local = new Registry();
            }
        }
    }
    return local;
}
Q2. Is a Spring singleton bean the same as the GoF Singleton?

No. Spring creates one instance per bean definition per ApplicationContext, and the class keeps a public constructor, so another context or plain new can create more. The container enforces the "one", not the class. This is why Spring beans are easy to replace in tests while GoF singletons are not.

Q3. A singleton service stores the current user in a field, and users start seeing each other's data. Why?

A singleton guarantees one instance, not thread safety. All request threads share that one field, so one request overwrites another's user. Keep request data in method parameters or local variables, or in a request-scoped bean, and keep singleton fields immutable or concurrent.

Q4. How do you unit-test code that calls PricingCache.getInstance() everywhere?

Refactor so that callers receive the cache through their constructor, typed as an interface, and only the composition root calls getInstance(). Tests then pass a fake. If you cannot refactor yet, a package-private reset method is a temporary workaround, but it lets tests change global state.

Q5. Your service runs as five pods. A scheduled job must run only once. Does a singleton help?

No. Each pod has its own JVM and therefore its own singleton. Cluster-wide "only one" needs coordination outside the JVM, such as a database lock (the ShedLock library does this for scheduled tasks), leader election through Kubernetes or ZooKeeper, or a single consumer on a queue.