Sub topic 10
Singleton Scope
This chapter assumes you know core Java, basic Spring dependency injection (@Component, @Autowired, @Configuration, @Bean), and how to run a Spring or Spring Boot application. It covers what singleton scope means in Spring, how it differs from the Singleton design pattern, and the mistakes that follow from sharing one instance.
What singleton scope means
Singleton is the default scope in Spring. For each bean definition, the container creates one instance and caches it. Every injection point and every getBean call for that definition receives the same object.
The scope applies per bean definition and per container. If you define two beans of the same class under different names, you get two instances. If an application has a parent and a child context, each context manages its own singletons.
Because of this, "singleton" in Spring is not the classic Singleton design pattern. The pattern guarantees one instance per class loader, enforced by the class itself (a private constructor and a static accessor). Spring guarantees one instance per bean definition per container, and the class stays an ordinary class.
The following table summarizes the difference.
| Aspect | Singleton design pattern | Spring singleton scope |
|---|---|---|
| Unit of uniqueness | Class, per class loader | Bean definition, per container |
| Who enforces it | The class (private constructor) | The container |
| Two instances of the class possible | No | Yes, with two definitions |
| Testable with substitutes | Hard | Easy, swap the definition |
Proving it with code
The default scope needs no annotation. The sketch below shows that two lookups return the same object, and that a second definition of the same class creates a second instance.
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class SingletonDemo {
static class Counter {
private int value;
synchronized int next() {
return ++value;
}
}
@Configuration
static class Config {
@Bean
Counter counter() {
return new Counter();
}
@Bean
Counter otherCounter() {
return new Counter();
}
}
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(Config.class)) {
Counter a = ctx.getBean("counter", Counter.class);
Counter b = ctx.getBean("counter", Counter.class);
Counter c = ctx.getBean("otherCounter", Counter.class);
System.out.println("a == b: " + (a == b));
System.out.println("a == c: " + (a == c));
a.next();
System.out.println("b sees: " + b.next());
}
}
}The output is:
a == b: true
a == c: false
b sees: 2a and b are one object, so the second call to next() returns 2. c is a different instance because it comes from a different definition.
When the instance is created
By default, the container creates all singletons during startup, as the last step of refreshing the context. This is eager initialization. It has a practical benefit: missing dependencies, circular constructor references and bad configuration fail at startup, not on the first request.
A singleton can opt out with @Lazy, which delays creation until first use. The next chapter covers that in detail. For now, remember that "singleton" describes how many instances exist, not when they are created.
Singleton beans also run their full lifecycle once. The constructor, initialization callbacks and any BeanPostProcessor steps happen one time. Destruction callbacks run when the context closes, which is why the earlier Main example closes the context with try-with-resources.
Declaring the scope explicitly
You rarely need to write the scope, but it is available:
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
@Service
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class PriceService {
}This is identical to omitting @Scope. Writing it is useful only when you want to make a design decision visible, for example next to a class that is deliberately stateless.
One instance, many threads
The main consequence of singleton scope is that many threads use the same object at once. In a web application, every request thread that calls a controller or service uses the same instance. Spring does not synchronize access to your bean. Thread safety is your responsibility.
The safest design is a stateless singleton. It has only final fields that hold other thread-safe collaborators (repositories, clients, other services) and keeps no per-call data in fields.
The following class is unsafe because it stores per-request data in a field:
import org.springframework.stereotype.Service;
@Service
public class UnsafeGreeter {
private String currentUser; // shared by every thread
public String greet(String user) {
this.currentUser = user;
// another thread may overwrite currentUser here
return "Hello, " + this.currentUser;
}
}Two concurrent calls can interleave, so one caller may receive a greeting meant for another. The fix is to keep the data in local variables or method parameters:
import org.springframework.stereotype.Service;
@Service
public class SafeGreeter {
public String greet(String user) {
return "Hello, " + user;
}
}If a singleton must hold mutable state, such as a cache or a counter, use thread-safe types (ConcurrentHashMap, AtomicLong) or explicit locking. Alternatively, move the state into a bean with a shorter scope and inject it correctly, a topic covered in later chapters.
Common mistakes
- Mutable fields set per call. The example above. Symptoms appear only under load, which makes them hard to reproduce.
- Assuming a new instance per injection. Injecting the same singleton into ten classes gives all ten the same object. Changing its state in one place changes it everywhere.
- Injecting a prototype into a singleton and expecting fresh instances. The singleton is created once, so its dependencies are resolved once. The prototype is injected a single time and then reused. Later chapters show
ObjectProviderand scoped proxies as the fix. - Relying on the pattern's guarantees. Code that assumes
new Counter()can never happen elsewhere will break, because nothing stops other code from creating its own instances. - Forgetting that two contexts mean two singletons. Tests that create several contexts, or parent and child contexts, produce separate instances of the same definition.
How the container stores singletons
Internally, the container keeps fully created singletons in a cache keyed by bean name, in DefaultSingletonBeanRegistry. When getBean is called, the container checks this cache first and returns the cached instance if present. Only on a miss does it run the creation steps. This is why the singleton lifecycle happens once.
The registry also tracks which singletons have destruction callbacks and in what order they were created. On close, the container destroys them in reverse dependency order, so a bean is destroyed before the beans it depends on. That ordering lets a service use its repository safely inside its own @PreDestroy method.
In practice, most singletons are created at startup, so the "miss" path runs once per bean while the context refreshes. Later lookups all take the "hit" path.
Choosing singleton
Use singleton scope for stateless services, repositories, configuration holders, clients for external systems and shared thread-safe resources such as connection pools. It is cheap, because there is one object to create and one to destroy, and it is the default for good reason.
Move to a different scope when a bean needs its own state per use (prototype) or per HTTP request or session (web scopes). The following chapters cover those scopes and how to wire them into singletons.
Exercise
A @Service class has a field private List<String> errors = new ArrayList<>();, and each call to validate(Order order) adds messages to it and returns it. Under load, callers sometimes see errors from other orders. Explain why this happens and how you would fix it.
Show answer
The service is a singleton, so one instance and one ArrayList are shared by every request thread. Concurrent calls add to and read the same list, so messages from different orders mix, and the unsynchronized ArrayList can also be corrupted. The fix is to make the service stateless. Create the list as a local variable inside validate and return it, so each call has its own list.
Exercise
You declare two @Bean methods that both return new Counter(), named counter and otherCounter. How many Counter instances exist in the context, and why is this consistent with singleton scope?
Show answer
Two. Singleton scope means one instance per bean definition per container, not one per class. Each @Bean method is a separate definition, so each gets its own cached instance.