When to use Singleton — appropriate use cases
Fast recall
Quick revision
Core answer
Interview-ready guide
Interview answer
I use one shared instance when a service or resource has one clear lifecycle owner for the application scope. For example, one Spring-managed HTTP client can share its connection pool across services and close that pool when the application context stops. The design still has to cover shutdown, concurrency, capacity, and refresh. I separate shared lifecycle from global access: constructor injection keeps the dependency visible and replaceable in tests. I do not put the current user, request, cart, or transaction in singleton fields because concurrent calls would share that state. Expensive creation is only a signal; the real decision is ownership, scope, and behavior.
When to use Singleton — appropriate use cases
Direct Answer
Use one shared instance when the application has a clearly owned service or resource whose lifecycle should match a defined container or process scope. Expensive creation alone is not enough; pools, caches, clients, and configuration objects need explicit lifecycle, concurrency, cleanup, and test boundaries. In Spring, prefer a singleton-scoped injected bean over a static global accessor, and never use shared fields for per-request or per-user state.
Common Mistakes & Pitfalls
- Sharing mutable state. A
UserSessionManagerSingleton withcurrentUserIdcauses concurrent requests to overwrite each other. - Singleton for domain objects.
Order/Cart/Productare regular objects with many instances. - Dodging DI. Calling
DiscountEngine.getInstance()instead of injecting it hides the dependency and hurts tests. - Manual Singleton in Spring.
@Servicesingleton scope already provides this with better integration.
Check your understanding
Answer these without looking back at the article.
- Why is a Singleton with mutable state dangerous in a web application?
- How does a connection pool like HikariCP use the Singleton idea?
- Why are domain entities a bad fit for Singleton?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.