Quick revision
The short answer
A Spring singleton can safely hold immutable configuration and references to other beans that are themselves thread-safe, because nothing in them changes after startup. Shared state that does change, such as caches and counters, must use thread-safe types like ConcurrentHashMap, AtomicLong or LongAdder, while non-thread-safe helpers like SimpleDateFormat should be replaced with immutable ones like DateTimeFormatter. Per-request data belongs in method parameters, local variables or request-scoped beans, and any singleton that does hold state should document how it stays safe.
What to remember
In this answer, we saw that a singleton is shared by every request thread, so its fields act like global variables. Immutable configuration and final references to thread-safe collaborators are safe. Caches and counters need ConcurrentHashMap, LongAdder or AtomicLong, and compound steps still need atomic methods such as computeIfAbsent(). Non-thread-safe helpers like SimpleDateFormat must be replaced by DateTimeFormatter or created per call. Per-request data belongs in parameters, locals or request-scoped beans, and any state a singleton keeps should come with a note on how it stays safe.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A Spring singleton can safely hold immutable configuration and references to other beans that are themselves thread-safe, because nothing in them changes after startup. Shared state that does change, such as caches and counters, must use thread-safe types like ConcurrentHashMap, AtomicLong or LongAdder, while non-thread-safe helpers like SimpleDateFormat should be replaced with immutable ones like DateTimeFormatter. Per-request data belongs in method parameters, local variables or request-scoped beans, and any singleton that does hold state should document how it stays safe.
Why this question is asked
Almost every bean in a Spring application is a singleton, and almost every one of them is called from many threads at once. Most of the time that is fine because the beans hold no changing state. The trouble starts when someone adds a field for a cache, a counter or a reused helper object. Interviewers ask this question to see whether we can tell safe state from unsafe state quickly, and whether we know the standard tools for the cases where state really must be shared. In this answer, we will recap why singletons are shared, sort the kinds of state into safe and unsafe, look at the right tool for caches and counters, see the classic SimpleDateFormat trap, and finish with where per-request data and documentation fit.
1A Quick Recap: One Instance, Many Threads
Singleton is Spring's default scope: the container creates one instance of the bean and injects that same instance everywhere. In a web application, the server runs each request on a thread from a pool, often up to 200 threads. So a single OrderService object may have dozens of threads inside its methods at the same moment.
Spring guarantees one thing here: the bean is fully constructed and its dependencies injected before any thread uses it, and that construction is safely published, so every thread sees the finished object. After that, Spring adds no locking. Whether the bean is thread-safe depends entirely on what its fields hold and how they change. A useful way to think about it is that every field of a singleton is effectively a global variable for the whole application.
2State That Is Safe to Keep
The first safe kind is configuration that is set once and never changes. A timeout read from application.yml, a base URL, or a feature setting stored in a final field is read by many threads but written by none after startup, so there is nothing to race on. The second safe kind is references to other beans that are themselves thread-safe: a repository, a RestClient, a JdbcTemplate or an ObjectMapper. The reference itself is final, and the object behind it is designed to be shared.
Making these fields final is more than style. A final field assigned in the constructor is guaranteed by the Java memory model to be visible, fully initialised, to every thread that sees the object. It also makes the intent clear to the next reader: this value does not change.
| State | Example | Safe as it is? | What to use |
|---|---|---|---|
| Immutable configuration | final Duration timeout | Yes | final field set in the constructor |
| Thread-safe collaborator | final JdbcTemplate jdbc | Yes | constructor injection |
| Cache | map of product id to price | Only with a concurrent type | ConcurrentHashMap, or Caffeine |
| Counter or statistic | requests served | Only with a concurrent type | LongAdder or AtomicLong |
| Non-thread-safe helper | SimpleDateFormat | No | DateTimeFormatter, or a new one per call |
| Per-request data | current user, running total | No | parameters, locals, request scope |
Notice that every field here is final and none of them is reassigned by a request. This bean can serve any number of threads without a single lock.
3Caches and Counters Need Thread-Safe Types
Some shared state is genuinely needed. A singleton might cache exchange rates or count how many requests it has served. A plain HashMap or a plain long field breaks here. Concurrent writes to a HashMap can lose entries and corrupt its internal structure, and count++ on a long is really three steps (read, add, write), so two threads can both read 41 and both write 42.
The java.util.concurrent package has types made for this. ConcurrentHashMap allows many threads to read and write at once, and its computeIfAbsent() runs the loading function at most once per missing key, atomically. For counters that many threads increment, LongAdder spreads the increments across several internal cells and adds them up when we read, so it scales better than AtomicLong under heavy contention; AtomicLong is the better choice when we need compare-and-set or an exact value on every read.
But there is a catch: a thread-safe container does not make a sequence of operations atomic. Calling containsKey() and then put() is still a race between the two calls, which is why computeIfAbsent() and merge() exist. And for a real cache with expiry and a size limit, a library such as Caffeine behind Spring's @Cacheable is usually better than a hand-written map that grows forever.
4Helpers That Must Not Be Shared
Some everyday classes are not thread-safe at all, and the classic example is SimpleDateFormat. It keeps the date it is working on in internal fields while it formats or parses, so two threads using one shared instance overwrite each other's work and get wrong dates or strange exceptions such as NumberFormatException. java.util.Calendar and some older XML and regex objects (a Matcher, for example) have the same problem.
Notice that the broken version even has a final field. final only stops the reference from being reassigned; it does nothing about the object's own internal state changing. The fix is to use an immutable replacement, which java.time provides, or to create the helper inside the method so each call has its own.
5Where Per-Request Data Belongs
Data that belongs to one request, such as the current user, a running total or a validation result, should never be stored in a singleton field. The simplest home is method parameters and local variables, which live on each thread's own stack. When the data must be available to several beans along the call chain, a request-scoped bean is the Spring answer: Spring injects a proxy into the singleton, and each call on that proxy is routed to the instance that belongs to the current HTTP request. Spring Security's SecurityContextHolder works on a similar per-thread idea for the authenticated user.
6Document the Threading Assumptions
When a singleton does hold shared state, the next developer needs to know how it stays safe. A short comment on the class or the field saying which state is shared, which type makes it safe, and which operations must stay atomic saves a later change from quietly breaking it. Some teams use the @ThreadSafe and @GuardedBy annotations from JCIP-style libraries so that static analysis tools can check the claims. The point is the same either way: state in a singleton should be a deliberate, written decision, not an accident.
7Follow-up questions
Is ObjectMapper safe to share as a singleton?
Yes, once it is configured. Jackson's ObjectMapper is thread-safe for reading and writing after its configuration is finished, which is why Spring Boot creates one shared instance. Changing its configuration while requests are using it is not safe, so all configuration should happen at startup.
When would you pick AtomicLong over LongAdder?
AtomicLong is better when we need an exact current value on every read or atomic operations like compareAndSet, for example to hand out sequence numbers. LongAdder is better for statistics that many threads increment often and that we read rarely, because it reduces contention by spreading the updates across cells.
8Conclusion
In this answer, we saw that a singleton is shared by every request thread, so its fields act like global variables. Immutable configuration and final references to thread-safe collaborators are safe. Caches and counters need ConcurrentHashMap, LongAdder or AtomicLong, and compound steps still need atomic methods such as computeIfAbsent(). Non-thread-safe helpers like SimpleDateFormat must be replaced by DateTimeFormatter or created per call. Per-request data belongs in parameters, locals or request-scoped beans, and any state a singleton keeps should come with a note on how it stays safe.
Open with
I start from the fact that a singleton is one instance shared by every request thread, so its fields behave like global variables. The safe state is anything that does not change after startup: immutable configuration in final fields, and final references to collaborators that are themselves thread-safe, like repositories, JdbcTemplate, RestClient or a configured ObjectMapper.
Then, if they want more
Final also gives the safe-publication guarantee of the memory model. If I really need shared mutable state, such as a cache or counters, I use concurrent types: ConcurrentHashMap with computeIfAbsent or merge so the compound operation is atomic, and LongAdder for high-contention counters or AtomicLong when I need compare-and-set.
For a real cache I would rather use Caffeine behind @Cacheable, because it handles size and expiry. I watch for helpers that are not thread-safe, the classic one being SimpleDateFormat, which keeps working state in fields and gives wrong dates when shared; DateTimeFormatter is immutable and is the replacement.
Per-request data never goes into a singleton field; it goes in parameters and locals, or in a request-scoped bean injected through a scoped proxy. Finally, when a singleton does keep state, I document which fields are shared and what keeps them safe, so a later change does not break it.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Core technologies
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Which kinds of state are acceptable in a Spring singleton, and how do you make shared...": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/68805bd59b/