Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

How would you prevent thread-safety bugs in singletons across many teams' Spring services?

I would make it a written convention that Spring singletons are stateless, holding only final fields that are immutable or thread-safe, and then enforce that convention with automated checks such as ArchUnit rules that fail the build on non-final fields in services and controllers. Code review and concurrency or load tests catch what the rules miss, and short training on the Java memory model explains why the rules exist. The aim is to make the safe pattern the default and the unsafe one visible.

Why this question is asked

One team can avoid thread-safety bugs through care and experience. Across twenty or fifty teams, with new joiners every month, care is not a strategy. These bugs are expensive because they are intermittent: they pass tests, appear only under load, and can mix one customer's data into another's response. Interviewers ask this at senior levels to see whether we think in systems: conventions, automation and teaching, rather than heroics in one codebase. In this answer, we will recap why singletons create these bugs, then build up the layers of prevention, from a clear convention, to automated checks, to reviews and tests, to training, and see what each layer costs and catches.

1A Quick Recap of Why the Bugs Happen

Spring creates most beans as singletons, one instance shared by the whole application. The web server runs requests on a pool of threads, so many threads run inside the same bean at once. A field on that bean is therefore shared by every request. If a request writes to it, for example to remember the current user or a running total, another request can read or overwrite it. The Java memory model adds a second problem: without final, volatile or a lock, one thread is not even guaranteed to see another thread's write.

Spring does nothing to prevent this. So the safety of every singleton in the company rests on its author knowing these facts. Our job as a technical leader is to reduce how much depends on each person remembering them.

2Layer 1: A Convention Everyone Can Follow

The first step is a rule simple enough to apply without thinking: beans in the service, controller and repository layers are stateless. Every field is final and set in the constructor, and it holds either an immutable value or a thread-safe collaborator. Shared mutable state, such as a cache, is allowed only with a concurrent type and a comment explaining how it stays safe.

A simple rule matters because it can be checked mechanically. Constructor injection supports it directly, since constructor-injected fields can be final, so the convention also becomes the default style in the company's service template. We write it down once in the engineering guidelines, with a short example of a broken bean and its fix, so reviewers can link to it instead of arguing from memory.

3Layer 2: Automated Checks in the Build

A convention that is not checked fades. ArchUnit is a library that lets us write architecture rules as ordinary unit tests over the compiled classes. A shared rule can fail the build when a class annotated with @Service or @RestController has an instance field that is not final; the same rule extends to @Component and @Repository with one more line each.

Java
@AnalyzeClasses(packages = "com.acme")
class SingletonRules {
@ArchTest
static final ArchRule beansHaveOnlyFinalFields =
fields()
.that().areDeclaredInClassesThat().areAnnotatedWith(Service.class)
.or().areDeclaredInClassesThat().areAnnotatedWith(RestController.class)
.and().areNotStatic()
.should().beFinal()
.because("singleton beans are shared by all request threads");
}
// Violation reported for:
// Field <com.acme.price.PriceController.total> is not final ... because singleton beans are shared
Step throughLayers of prevention
  1. Conventionsingletons are stateless; only final, immutable or thread-safe fields
  2. Template and starterconstructor injection and shared rules come by default
  3. Build checksArchUnit and static analysis fail on mutable fields
  4. Code reviewreviewers look for state, compound operations and unsafe helpers
  5. Concurrency testsload tests prove shared components under parallel calls
  6. Trainingthe memory model and proxy basics explain the rules

6 layers, from the top down. Step through them one at a time.

Each layer catches some of what the one above it misses.

We ship this rule in a shared test library or starter, so every service picks it up with a single dependency, and the platform team maintains it in one place. The rule will not catch everything. A final field can still hold a mutable HashMap or a SimpleDateFormat, so a second rule can forbid known unsafe field types such as SimpleDateFormat, java.util.HashMap and ArrayList in beans. Static analysis tools such as SpotBugs or Error Prone add checks for common concurrency mistakes. For the rare legitimate exception, we allow an explicit annotation, such as a company @ThreadSafeState, so the exception is visible and searchable rather than silent.

4Layer 3: Code Review That Knows What to Look For

Automated rules catch the obvious cases; reviewers catch the subtle ones. We give reviewers a short checklist in prose form in the review guide: any field assigned outside the constructor, any final field holding a mutable collection, compound operations such as checking a map and then putting into it, and helpers known not to be thread-safe. Reviewers also question new ThreadLocal usage, because with pooled threads a value left behind leaks into the next request.

The cost is reviewer time, so we keep the checklist short and focus it on changes to beans, not every line. Senior engineers in each team act as the people others can ask, which spreads the knowledge without a central bottleneck.

5Layer 4: Concurrency and Load Tests for Shared Components

Some components hold state on purpose: caches, rate limiters, connection managers, in-memory aggregators. For those, a normal unit test proves nothing, because it runs on one thread. We ask for a concurrency test that runs the component from many threads with known inputs and checks every result. For example, 100 threads each adding 1,000 to a counter must end at exactly 100,000, and 500 parallel requests to an endpoint, each with its own user, must each get their own user back.

We add a similar check to the service's load test suite for endpoints that touch shared state. These tests are slower, so they run in a nightly or pre-release stage rather than on every commit, but they turn an intermittent production bug into a repeatable failure.

6Layer 5: Training on the Memory Model Basics

Rules without understanding lead to workarounds, such as making a field volatile to silence the checker without fixing the race. So we run a short session for new joiners and include it in the onboarding material. It covers what a singleton is, how request threads share it, the difference between visibility (volatile, final) and atomicity (locks, atomic types), and two or three real examples from our own incidents. One hour, done once per person, pays for itself the first time it prevents a data leak between users.

Finally, we measure. We track how many violations the rules find and how many concurrency bugs reach production each quarter. If the second number does not fall, we revisit which layer is failing.

7Follow-up questions

Won't a rule on non-final fields be too strict?

It is strict on purpose, because the safe pattern is easy to follow with constructor injection. The few legitimate cases, such as a lazily built cache, can use a concurrent type in a final field, which passes the rule. For truly special cases we allow an explicit, reviewed exception annotation rather than weakening the rule for everyone.

How would you roll the ArchUnit rule out to existing services?

First in warning mode, reporting violations without failing the build, so teams can see their count. ArchUnit supports freezing existing violations so that only new ones fail. Then we set a date by which teams fix the existing ones, starting with services that handle personal data.

Does this also apply to non-web code, such as Kafka listeners?

Yes. A listener container with concurrency greater than one calls the same singleton listener from several consumer threads, and scheduled tasks and @Async methods run on their own pools. Any singleton reached from more than one thread needs the same rules.

8Conclusion

In this answer, we built layered prevention for thread-safety bugs in singletons across many teams. A simple convention says beans are stateless with only final, immutable or thread-safe fields. ArchUnit and static analysis enforce it in every build through a shared library. Reviews catch subtler cases, concurrency and load tests prove the components that hold state on purpose, and short training on the memory model explains why the rules exist. Measuring violations and incidents tells us which layer needs work.

What to say in the interviewAbout 90 seconds aloud

Open with

I would treat it as a platform problem rather than relying on each engineer remembering the rules. First, a clear convention: services, controllers and repositories are stateless, every field is final and set through the constructor, and it holds either an immutable value or a thread-safe collaborator.

Then, if they want more

Shared mutable state is allowed only with a concurrent type and a comment explaining why it is safe. Second, I would automate the convention.

I would put ArchUnit rules in a shared test starter that fail the build on non-final instance fields in Spring stereotypes, plus rules against known unsafe types like SimpleDateFormat or a plain HashMap in beans, and I would roll it out with frozen existing violations so only new ones fail.

Third, code review with a short guide on what to look for: fields written by requests, check-then-act on collections, ThreadLocal left behind. Fourth, for components that hold state on purpose, like caches or rate limiters, concurrency tests that hit them from many threads with known inputs, and load tests on endpoints that touch shared state.

Fifth, a short onboarding session on the memory model basics, visibility versus atomicity, and how singletons are shared, using our own incidents as examples. Then I would track violations and production incidents to see whether it is working.

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 "How would you prevent thread-safety bugs in singletons across many teams' Spring services?": https://scrivio-interview-library.netlify.app/spring-boot/bean-scopes/5cd408ba94/