Singleton Design Pattern in Java
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
| Component | Responsibility |
|---|---|
| Private constructor | Prevents other classes from creating instances |
| Static instance field | Holds the single object, usually private static final |
| Static accessor | getInstance() returns that object, creating it first if the singleton is lazy |
| Client | Any 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.
ExchangeRateRegistryhas aprivate staticfield of its own type: the single instance. The arrow back to the class with multiplicity 1 shows that self-reference.- The constructor is marked
-(private), so the clients have no way to call it. getInstance()is+(public) and static, the only way in.- Both services depend on the registry (dashed "uses" arrows) and receive the same object.
5. Step-by-Step Execution Flow
- The first time code touches
ExchangeRateRegistry, the JVM loads and initialises the class. - 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.
CheckoutServicecallsgetInstance()and gets the reference stored inINSTANCE.InvoiceServicecallsgetInstance()and gets the same reference. No new object is created.- 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 oneRuntimeobject of the running application, andCollections.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:
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"));
}
}
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
newagain.
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.
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
INSTANCEis created eagerly, when the class is initialised.- The private constructor blocks
newfrom other classes. getInstance()just returns the field, so it needs no locking.
Expected output
Loading rates from the bank feed...
Checkout uses USD = 83.45
Invoice uses USD = 83.45
Same object? true
How it runs
- The first
getInstance()call initialises the class, which loads the rates once. - The second call returns the same object.
- The update is visible to both services, and
==confirms one object.
Practical Example: Lazy, Thread-Safe Order-Number Generator
Problem: create the generator only when first needed, and never hand out a duplicate number while eight threads call it at once.
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class OrderNumberGeneratorDemo {
static final AtomicInteger CONSTRUCTOR_CALLS = new AtomicInteger(); // test hook: counts instances
static final class OrderNumberGenerator {
private final AtomicLong sequence = new AtomicLong(1000);
private OrderNumberGenerator() {
CONSTRUCTOR_CALLS.incrementAndGet();
}
// Holder idiom: Holder is initialised on the first getInstance() call, and the JVM makes that thread-safe
private static final class Holder {
private static final OrderNumberGenerator INSTANCE = new OrderNumberGenerator();
}
static OrderNumberGenerator getInstance() {
return Holder.INSTANCE;
}
String next() {
return "ORD-" + sequence.incrementAndGet();
}
}
public static void main(String[] args) {
System.out.println("Instances before first use: " + CONSTRUCTOR_CALLS.get()); // lazy: nothing created yet
Set<String> orderNumbers = ConcurrentHashMap.newKeySet();
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 1_000; i++) {
pool.submit(() -> orderNumbers.add(OrderNumberGenerator.getInstance().next())); // 8 threads race for the instance
}
} // close() waits for all tasks
System.out.println("Instances after 1000 calls: " + CONSTRUCTOR_CALLS.get());
System.out.println("Unique order numbers: " + orderNumbers.size());
System.out.println("Next order number: " + OrderNumberGenerator.getInstance().next());
}
}
Important classes and methods
Holderis a nested class that the JVM initialises only whengetInstance()first readsHolder.INSTANCE. This is the initialisation-on-demand holder idiom: lazy and thread-safe withoutsynchronizedorvolatile.AtomicLongmakesnext()thread-safe. One instance alone would not prevent duplicates.CONSTRUCTOR_CALLSexists only to prove how many instances were created.
Expected output
Instances before first use: 0
Instances after 1000 calls: 1
Unique order numbers: 1000
Next order number: ORD-2001
How it runs
- Before any call, the counter is 0: nothing has been created.
- 1,000 tasks on 8 threads call
getInstance(). The JVM initialisesHolderonce and makes the other threads wait. - Numbers 1001 to 2000 are handed out with no duplicates, so the next one is 2001.
Real-World Enterprise Example: Enum Audit Trail
Problem: a payment audit trail must stay unique even when it is serialized or attacked with reflection, and the payment code must still be testable.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serial;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class AuditTrailDemo {
// Abstraction the business code depends on
interface AuditTrail {
void record(String event);
List<String> events();
}
// Enum singleton: one instance per class loader, safe against serialization and reflection
enum PaymentAuditTrail implements AuditTrail {
INSTANCE;
private final List<String> events = new CopyOnWriteArrayList<>(); // thread-safe state
@Override
public void record(String event) { events.add(event); }
@Override
public List<String> events() { return List.copyOf(events); }
}
// A classic class-based singleton, for comparison
static final class ClassicAuditTrail implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
private static final ClassicAuditTrail INSTANCE = new ClassicAuditTrail();
private ClassicAuditTrail() { }
static ClassicAuditTrail getInstance() { return INSTANCE; }
}
// Client gets the audit trail through its constructor, so tests can pass a fake
static final class PaymentService {
private final AuditTrail audit;
PaymentService(AuditTrail audit) { this.audit = audit; }
void pay(String orderId, String amount) {
audit.record("PAID " + orderId + " " + amount);
}
}
static Object roundTrip(Object original) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(original);
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
return in.readObject();
}
}
public static void main(String[] args) throws Exception {
PaymentService payments = new PaymentService(PaymentAuditTrail.INSTANCE);
payments.pay("ORD-1001", "Rs. 2499.00");
payments.pay("ORD-1002", "Rs. 640.00");
System.out.println("Audit events: " + PaymentAuditTrail.INSTANCE.events());
// 1. Serialization
System.out.println("Enum survives serialization: " + (roundTrip(PaymentAuditTrail.INSTANCE) == PaymentAuditTrail.INSTANCE));
System.out.println("Classic survives serialization: " + (roundTrip(ClassicAuditTrail.getInstance()) == ClassicAuditTrail.getInstance()));
// 2. Reflection
Constructor<ClassicAuditTrail> classicConstructor = ClassicAuditTrail.class.getDeclaredConstructor();
classicConstructor.setAccessible(true);
System.out.println("Reflection made a second classic instance: " + (classicConstructor.newInstance() != ClassicAuditTrail.getInstance()));
Constructor<?> enumConstructor = PaymentAuditTrail.class.getDeclaredConstructors()[0];
enumConstructor.setAccessible(true);
try {
enumConstructor.newInstance("COPY", 1);
} catch (IllegalArgumentException | InvocationTargetException e) {
System.out.println("Reflection on the enum failed: " + e.getMessage());
}
}
}
Important classes and methods
PaymentAuditTrailis an enum singleton. The JVM guarantees one instance of each constant, keeps it unique through serialization, and refuses to create enum objects by reflection.- It implements the
AuditTrailinterface, andPaymentServicereceives it through its constructor. Business code never calls the singleton directly, so a test can pass a fake. ClassicAuditTrailshows the two weaknesses of a class-based singleton.
Expected output
Audit events: [PAID ORD-1001 Rs. 2499.00, PAID ORD-1002 Rs. 640.00]
Enum survives serialization: true
Classic survives serialization: false
Reflection made a second classic instance: true
Reflection on the enum failed: Cannot reflectively create enum objects
How it runs
- Two payments write to the one audit trail.
- Serializing and reading back the enum returns the same constant. The classic class returns a new object, because it has no
readResolve()method. setAccessible(true)lets reflection call the classic private constructor, creating a second instance.- The same trick on the enum throws
IllegalArgumentException.
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, addreadResolve()returningINSTANCE. - 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
| Aspect | Singleton | Static utility class | Spring singleton bean | Flyweight |
|---|---|---|---|---|
| Instances | Exactly one per class loader | None | One per application context | One per distinct shared state |
| Holds state | Yes | Should not | Usually not | Only immutable shared state |
| Implements interfaces | Yes | No | Yes | Yes |
| Who enforces "one" | The class itself | Not applicable | The container | A factory with a cache |
| Testability | Weak unless injected | Weak | Strong | Good |
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.