What is Singleton?
As part of my Path to Java Architect journey, I've started revisiting Java design patterns.
I'm planning to study each pattern, implement it myself, test it, and document what I learn along the way.
Starting with the Singleton Design Pattern.
From what I understood, Singleton is used when we want only one instance of a class and a common way to access it.
For example, in a payment application, different services might need to read the same configuration. Instead of creating multiple configuration manager objects, we can create one and share it.
The basic idea is simple. But when multiple threads are involved, we need to be a little careful.
Lazy Singleton
I started with the simplest implementation.
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}A few things I noted:
- The constructor is private, so other classes cannot directly create an object.
- The instance is stored in a static variable.
- The object is created only when
getInstance()is called for the first time. - Subsequent calls return the same object.
This looks fine in a single-threaded application.
But what happens if two threads call it at the same time?
Let's say T1 checks instance == null and finds it true. Before T1 creates the object, T2 also checks and finds it null. Now both threads can create separate objects.
nullnullThat's the problem with this implementation. It doesn't guarantee a single instance when multiple threads access it concurrently.
Using synchronized
To solve this, I tried adding synchronized to the method.
public static synchronized SingletonMultithreaded getInstance() {
if (instance == null) {
instance = new SingletonMultithreaded();
}
return instance;
}Here, only one thread can enter the method at a time.
- T1 enters the method and acquires the lock.
- T2 tries to enter but has to wait.
- T1 creates the object and releases the lock.
- T2 enters, finds the object already created, and returns the same instance.
This solves the problem of creating multiple objects.
Let's say 100 threads are trying to access it. They all have to acquire the lock one by one.
The method is thread-safe, but this can introduce unnecessary locking overhead.
This is what led me to Double-Checked Locking.
Double-Checked Locking (DCL)
Here is the implementation I tried.
public class SingletonWithDCL {
private static volatile SingletonWithDCL instance;
private SingletonWithDCL() {}
public static SingletonWithDCL getInstance() {
if (instance == null) {
synchronized (SingletonWithDCL.class) {
if (instance == null) {
instance = new SingletonWithDCL();
}
}
}
return instance;
}
}Initially, I was confused about why we need two null checks and the volatile keyword.
After going through the execution step by step, this is what I understood.
Check if the object already exists. If it does, return it without taking the lock.
If it doesn't exist, try to acquire the class lock. Only one thread can enter at a time.
T1 might have created the object while T2 was waiting. The second check prevents T2 creating another one.
Threads that skip the lock still need to safely see the fully initialised object.
Why check twice?
Imagine T1 and T2 both passed the first null check. T1 acquires the lock and creates the object. T2 waits.
When T2 finally acquires the lock, the object already exists. The second check prevents T2 from creating another one.
Why volatile?
This was the part I spent more time understanding.
In DCL, some threads can return the instance without entering the synchronized block.
Without volatile, Java doesn't guarantee that those threads will see the object's fully initialised state.
volatile provides the memory visibility and ordering guarantees needed to publish the object safely.
Trying it with 100 threads
After understanding the implementations, I wanted to try them with multiple threads.
I created a simple payment configuration example using two classes:
PaymentConfig— using a synchronized method.PaymentConfigWithDCL— using Double-Checked Locking.
I used Executors.newFixedThreadPool(100) to submit 100 tasks and call the Singleton methods.
My idea was to compare the time taken by both approaches. I used System.nanoTime() to measure the execution time.
One thing I understood from this experiment is that the execution time doesn't depend only on synchronization. It also includes thread scheduling and executor overhead.
So running 100 tasks once doesn't prove how much faster DCL is.
What I can say from the implementation is that DCL avoids acquiring the lock on every call after the instance is created.
I still need to explore JMH to measure the actual performance difference properly.
Do we really need Singleton in Spring Boot?
While learning this, another question came to mind: in Spring Boot, do we really need to create Singleton classes manually?
In most cases, we don't. Spring manages beans with singleton scope by default.
For example, for payment configuration, we can use:
@ConfigurationProperties(prefix = "payment")
public record PaymentSettings(
int timeoutSeconds,
int maxRetries
) {}With configuration-properties scanning or explicit registration enabled, Spring creates and manages this configuration bean.
Other services can simply inject it through constructor injection.
This approach is cleaner than writing a manual Singleton with getInstance().
One thing to remember is that a Spring singleton bean is shared within its application context. It isn't a single object shared across multiple application instances or Kubernetes pods.
My takeaways from Day 1
These are the main things I learned:
- Singleton is used to control object creation and provide a shared instance.
- Lazy Singleton is simple, but it isn't thread-safe.
- Adding
synchronizedprevents multiple threads from creating different instances. - Synchronizing the entire getter means every call still needs to acquire a lock.
- Double-Checked Locking avoids repeated locking after initialisation.
volatileis important for safe publication in DCL.- Even if Singleton creation is thread-safe, its mutable fields and methods may not be.
- In Spring Boot, I would usually prefer Spring-managed beans instead of manually implementing Singleton.
The main thing I learned today wasn't just how to write a Singleton class.
It was understanding why synchronization is needed, what problem it solves, and why DCL uses volatile.
I also realised that just because a design pattern solves a problem doesn't mean we need to use it everywhere.
I've committed my implementations to GitHub as part of this learning journey.
These are my personal learning notes, which I'm sharing here in case they're useful to anyone revisiting Java design patterns.
Not published yet — this is what I plan to learn next.