Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

Code reviews across your teams repeatedly find shared mutable HashMaps and ArrayLists in Spring singleton beans. What standard for shared mutable state would you set, and how would you make it stick?

The standard I would set starts with a default: Spring singleton beans are stateless, and request data lives in method parameters or request-scoped objects. When state must be shared, prefer an immutable snapshot swapped through a volatile field or an AtomicReference; when a map really is updated concurrently, use ConcurrentHashMap with its atomic methods, and document the thread-safety of every shared field. To make it stick, add static analysis rules and review checklist items that flag mutable fields in singletons, and teach the reasons with our own incidents rather than only stating the rule.

Why this question is asked

A Spring singleton bean is one object shared by every request thread in the application, which is easy to forget because the code looks like ordinary single-threaded Java. A HashMap field used as a cache, an ArrayList collecting results, or a SimpleDateFormat field all work in development and fail in production as lost updates, corrupted maps or garbled dates. When reviews keep finding the same pattern across teams, it is no longer an individual mistake; it is a missing standard. Interviewers ask this at senior levels to see how a candidate defines a rule that is simple enough to follow and then makes it last. In this answer, we will recap why singletons are shared, write the standard layer by layer, and then look at enforcement and teaching.

1A Quick Recap: Why Singleton Beans Are Shared

By default, Spring creates one instance of each bean and injects that instance everywhere. In a web application served by, say, 200 Tomcat threads, or by thousands of virtual threads, every request calls the same object at the same time. Any field that a method changes is therefore shared mutable state, touched by many threads without any coordination unless we add it.

HashMap and ArrayList are not built for that. Concurrent puts into a HashMap can lose entries or corrupt its internal structure, and an ArrayList can lose elements or throw. The bugs are rare, load-dependent and almost impossible to reproduce on a laptop, which is why they survive testing.

Java
@Service
class PriceService {
private final Map<String, Price> cache = new HashMap<>(); // shared by every request thread
Price price(String id) {
Price p = cache.get(id);
if (p == null) {
p = client.fetch(id);
cache.put(id, p); // concurrent puts: lost or corrupted entries
}
return p;
}
}

2The Standard, Layer by Layer

The first rule is the default: singleton beans hold only dependencies and configuration, set at construction and never changed. Everything about a request travels in method parameters, local variables or a request-scoped object. Final fields assigned in the constructor make this visible in the code. Most beans in a typical service need nothing more.

The second rule covers state that is read often and changed rarely, such as configuration reloaded from a control plane or a lookup table refreshed every few minutes. That state is held as an immutable snapshot, for example a record containing Map.copyOf, in a volatile field or an AtomicReference. Updates build a new snapshot and swap the reference, and readers take one consistent version per request.

The third rule covers state that is genuinely updated concurrently, like counters or in-process caches. Use ConcurrentHashMap and its atomic methods, merge, compute, computeIfAbsent, rather than check-then-act sequences, and prefer a real cache library such as Caffeine when expiry or bounds are needed. Every shared mutable field carries a short comment or annotation saying how it is made thread-safe.

Java
@Service
class PriceService {
// rule 3: concurrent updates through a cache library, no I/O under a map lock
private final AsyncLoadingCache<String, Price> cache;
// rule 2: rarely changed shared state as an immutable snapshot
private final AtomicReference<PricingRules> rules = new AtomicReference<>(PricingRules.EMPTY);
PriceService(PriceClient client) { // rule 1: dependencies only, final fields
this.cache = Caffeine.newBuilder().maximumSize(50_000)
.expireAfterWrite(Duration.ofMinutes(5)).buildAsync(client::fetch);
}
void reload(PricingRules newRules) { rules.set(newRules); } // thread-safety: AtomicReference swap
}
Step throughWhere does this state belong?
  1. Is it about one request?
    YesMethod parameter or request scopeNoIt is shared state
  2. Changed rarely, read often?
    YesImmutable snapshot in AtomicReferenceNoUpdated concurrently
  3. Needs expiry or bounds?
    YesCaffeine or similar cacheNoConcurrentHashMap with atomic methods
  4. Document the thread-safety of the fieldone line per shared field

4 steps in order. Play them, or step through them one at a time.

3Making It Stick: Tools

A written standard decays unless something checks it. Static analysis can find most violations automatically. An ArchUnit test can fail the build when a class annotated with @Service, @Component or @RestController has a non-final field, or a field whose type is HashMap, ArrayList or SimpleDateFormat. Tools like SpotBugs, Error Prone or Sonar have related checks for unsynchronized access and mutable static fields; check which rules your version offers.

These rules should start as warnings with a link to the standard, while teams fix the existing findings or add an explicit suppression with a reason. Once the backlog is clean, they become build failures. A review checklist item, does any singleton have a field that changes after construction, catches what the tools miss, such as a mutable object hidden behind a final field.

4Making It Stick: Teaching With Real Incidents

Rules without reasons are followed until a deadline arrives. The teaching material should therefore show our own failures: the order-total bug where two requests shared a mutable field in a singleton and customers saw each other's totals, or the cache HashMap that went into a corrupted state under load. A ten-minute walkthrough of a real incident, with the code, the symptom and the fix, makes the rule obvious in a way a style guide never does.

I would include it in onboarding for every new engineer, link it from the static analysis messages, and revisit it whenever a new incident of the same class happens. If the pattern still recurs after the tools are in place, that is a signal to look for the gap: perhaps a framework feature or a code generator that produces stateful beans, which then needs its own fix.

5Follow-up questions

Is request scope a good alternative to stateless singletons?

It is useful for genuinely per-request objects, but it adds a proxy and a lookup on every call, and it fails outside a web request, for example in async tasks or message listeners. Passing data as method parameters is simpler and works everywhere, so request scope should be the exception.

What about ThreadLocal for per-request state?

It works with a fixed thread pool, but values leak into the next request if not cleared, and with virtual threads or reactive code a request may hop threads. Spring already manages its own thread-bound context where needed; in our code, explicit parameters or ScopedValue on recent JDKs are safer.

How do you handle legacy code with many violations?

Run the checks, record the existing findings as a baseline so the build only fails on new violations, and fix the baseline by risk: shared maps and lists touched on hot paths first, harmless fields later. Track the baseline count down over a few quarters.

6Conclusion

In this answer, we set a standard for shared mutable state in Spring singleton beans. The default is stateless singletons with request data in parameters or request-scoped objects; shared state that changes rarely becomes an immutable snapshot swapped through a volatile field or AtomicReference; concurrently updated maps use ConcurrentHashMap with atomic methods, and every shared field documents its thread-safety. To make it stick, static analysis rules and review checklist items flag mutable fields in singletons, and the reasons are taught with real incidents rather than only stated.

What to say in the interviewAbout 100 seconds aloud

Open with

The root of the problem is that a Spring singleton is one object used by every request thread at once, but the code looks single-threaded, so people add a HashMap cache or a list field without thinking.

Then, if they want more

My standard would have three layers. The default is stateless singletons: only final fields for dependencies and configuration, set in the constructor, and anything about a request goes in method parameters or a request-scoped object.

Second, for shared state that's read a lot and changed rarely, like reloaded configuration, use an immutable snapshot held in a volatile field or an AtomicReference and swap the whole thing on update, so every request sees one consistent version.

Third, for state that's really updated concurrently, use ConcurrentHashMap with its atomic methods like merge and computeIfAbsent, or a cache library like Caffeine if it needs expiry, and every shared field gets a one-line note on how it's made thread-safe.

To make it stick, I'd automate it: an ArchUnit test or static analysis rule that flags non-final fields, or fields of types like HashMap, ArrayList or SimpleDateFormat, in Spring components, starting as warnings with a baseline and then failing the build. I'd add it to the review checklist for things the tools miss.

And I'd teach it with our own incidents, showing the real bug where requests shared a field and saw wrong data, because people remember the incident and the reason far better than the rule.

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.
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 "Code reviews across your teams repeatedly find shared mutable HashMaps and ArrayLists in...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/b0c99a4534/