Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

Code reviews in your organisation often argue about mutable shared state: static caches, singletons holding request data, and long methods with many reassigned local variables. What coding guidelines on variables and scope would you set, and how would you enforce them?

I would set a few clear rules: declare every variable in the narrowest scope and close to its use, keep methods short and never reuse a variable for a different meaning, prefer final or effectively final locals and immutable objects such as records and unmodifiable collections, and never store request or user data in static fields or singletons, passing it as parameters or through scoped beans and ScopedValue instead. Any remaining static mutable state needs a documented owner and thread-safety approach. The rules are enforced by static analysis with Error Prone, Sonar and Checkstyle and taught through examples in the guide, so reviews stop being debates about personal preference.

Why this question is asked

Arguments about shared state in code review are a symptom: people disagree because the rules live in individual heads. Meanwhile the bugs are real. A singleton that stores the current user leaks one customer's data into another's response under load, a static cache grows until the service runs out of memory, and a 200-line method with a variable reassigned six times hides the logic error nobody can find. Interviewers ask senior engineers this to see how they turn experience into guidelines that scale, and how they enforce them without becoming the bottleneck. In this answer, we will recap why shared mutable state is costly, set guidelines for scope, immutability, request data and static state, and then plan enforcement and adoption.

1A Quick Recap: Why Shared Mutable State Is Expensive

State is mutable when it can change after creation, and shared when more than one piece of code, or more than one thread, can reach it. The combination is what costs us. To understand a line that reads a shared mutable value, a reader has to know every place that might have changed it and in what order. With threads, the order is not even fixed, so the result can depend on timing, which is how data races and lost updates appear only under production load.

Scope is the other half. The wider a variable's scope, the more code can touch it. A local declared at the top of a long method and reassigned throughout is a small version of the same problem: every reassignment is a place the reader must track. So all the guidelines push in one direction: less sharing, narrower scope, fewer changes.

2Guideline 1: Narrowest Scope, One Meaning per Variable

Declare a variable where it is first needed, in the smallest block that uses it, and give it one meaning for its whole life. Reusing a variable called result first for a raw response and later for a parsed object saves a line and costs every reader a moment of confusion. Keep methods short enough that a reader can hold them in their head; a rough threshold such as 30 to 40 lines is a prompt to extract a method, not a law.

Java
// Before: one variable, three meanings, wide scope
String value = request.getParameter("qty");
value = value.strip();
// ... 40 lines later
value = String.valueOf(Integer.parseInt(value) * price); // now it is a total
// After: each value has its own name and is assigned once
final String rawQty = request.getParameter("qty");
final int quantity = Integer.parseInt(rawQty.strip());
final long totalCents = Math.multiplyExact(quantity, priceCents);

Notice that the second version is not longer in any way that matters, and each name now says what the value is. Because every local is assigned once, a reader can trust a name everywhere it appears.

3Guideline 2: Prefer Final Locals and Immutable Objects

Prefer locals that are final or effectively final, and objects that cannot change. Records give us immutable data carriers in one line, List.of, Map.of and List.copyOf give unmodifiable collections, and builders or withers produce changed copies instead of mutating in place. An immutable object can be shared between threads with no locking at all, which removes the hardest category of bugs.

The guideline should be honest about limits: records are shallowly immutable, so a record holding an ArrayList can still change through it. The rule is to copy mutable inputs in the compact constructor, for example items = List.copyOf(items), so the record really is immutable.

4Guideline 3: No Request or User Data in Static Fields or Singletons

This is the rule with the most serious consequences, so it is a hard ban rather than a preference. Spring beans are singletons by default: one instance serves every request on every thread. A field on such a bean that holds the current user, the current tenant or a request's data is shared by all concurrent requests.

Java
@Service
class InvoiceService {
private User currentUser; // BUG: shared by all requests
Invoice create(User user, Order order) {
this.currentUser = user; // thread A sets Alice
return build(order); // thread B sets Bob before A reads it
}
private Invoice build(Order order) {
return new Invoice(currentUser, order); // A may build Alice's order with Bob
}
}
// Fixed: pass the data as a parameter
Invoice create(User user, Order order) { return build(user, order); }
Step throughTwo requests sharing a singleton field
Thread A (Alice)InvoiceServiceThread B (Bob)
create: currentUser = Alice
create: currentUser = Bob
build: reads currentUser
Invoice for Bob's details
build: reads currentUser
Invoice for Bob

6 messages in order. Play them, or step through them one at a time.

One shared field, two concurrent requests, one customer's data in another's invoice.

Two threads interleave, and Alice's invoice is created with Bob's details: a data leak that no unit test with one thread will find. The fix is to pass request data as parameters. Where it must travel through many layers, Spring's request-scoped beans or the security context already provide per-request storage, and ScopedValue gives a value bound to a block of code and its callees that cannot be changed and disappears when the block ends; it became a final feature in Java 25, so check your Java version. ThreadLocal is the older tool, but with thread pools it must always be cleared in a finally block, or the next request on that thread inherits the old value.

5Guideline 4: Static Mutable State Needs an Owner

Some shared mutable state is legitimate: a cache, a metrics registry, a connection pool. The rule is that each piece has a documented owner and thread-safety approach, written next to the declaration: which class may change it, which concurrent structure or lock protects it, and what bounds its size. A static HashMap used as a cache fails all three. A bounded Caffeine cache held by one Spring bean, with a maximum size and an expiry, passes them, and it is easy to spot in review because the comment and the type agree.

6Enforcing and Adopting the Guidelines

Guidelines that rely on reviewers remembering them produce the same arguments we started with. So we encode what can be checked. Error Prone has checks for mutable fields in classes that should be immutable and for unsafe static state, Sonar flags non-final static fields and methods that are too long or too complex, and Checkstyle enforces declaration rules such as final parameters or variable declaration distance. ArchUnit tests can express our own rules, for example that classes annotated with @Service have only final fields. Check your tool versions for exact rule names, start new rules as warnings with a baseline for existing code, and turn them into build failures for new code once teams are used to them.

The written guide is short, and each rule comes with a before and after example from our own codebase, like the ones above, because engineers copy examples more reliably than they apply principles. Reviewers then link to the rule instead of arguing taste. Finally, we watch outcomes: fewer concurrency incidents, fewer review comments on the same topics, and feedback from new joiners. If a rule creates more friction than it prevents, we change the rule for everyone instead of accepting quiet exceptions.

7Follow-up questions

Isn't requiring final everywhere just noise?

On every local, it can be. That is why the guideline says final or effectively final: the important property is that a variable is assigned once, and the compiler already tracks that. I would require final on fields, where it guarantees safe publication and documents immutability, and leave the keyword on locals to team preference.

What about long methods in legacy code?

We do not rewrite them for style. The rule applies to code being changed: when someone touches a long method, they extract the part they need to understand and leave it better, which keeps diffs reviewable and spreads the improvement where it matters most.

When is a ThreadLocal still acceptable?

For per-thread resources that are expensive to create and not tied to a request, such as a non-thread-safe formatter, or in framework code that clears it reliably. For request data in application code, parameters, scoped beans or ScopedValue are clearer and do not leak between requests.

8Conclusion

In this answer, we set guidelines for variables and shared state: narrowest scope and one meaning per variable, final locals and immutable objects such as records and unmodifiable collections, a hard ban on request or user data in static fields and singletons in favour of parameters, scoped beans and ScopedValue, and a documented owner and thread-safety approach for any remaining static mutable state. We enforce them with Error Prone, Sonar, Checkstyle and ArchUnit, teach them with examples from our own code, and judge them by incidents and review friction.

What to say in the interviewAbout 100 seconds aloud

Open with

I would start by explaining why we care: shared mutable state forces every reader to know who else might change a value and when, and with threads the order is not even fixed, which is how we get bugs that only appear under load.

Then, if they want more

Then I would set four guidelines. First, narrow scope: declare variables where they are used, keep methods short, and never reuse one variable for different meanings. Second, prefer final or effectively final locals and immutable objects, records, List.copyOf and so on, because immutable objects can be shared between threads with no locking.

Third, a hard ban on request or user data in static fields or singleton beans. Spring beans are singletons, so a field holding the current user is shared by every request, and two concurrent requests can mix customers' data.

Request data goes through parameters, request-scoped beans or ScopedValue, which is final in Java 25, and ThreadLocal only with a finally that clears it. Fourth, any static mutable state, like a cache, needs a documented owner, a thread-safe structure and a size limit. For enforcement, I would not rely on reviewers.

I would use Error Prone and Sonar for mutable static fields and long methods, Checkstyle for declaration rules, and ArchUnit for our own rules, like service beans only having final fields, introduced as warnings with a baseline and then as build failures for new code.

The guide itself would be short, with before and after examples from our codebase, so reviewers link to it instead of debating taste.

About this answer

Last updated
12 November 2026
Versions it names
Java 25
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 in your organisation often argue about mutable shared state: static caches...": https://scrivio-interview-library.netlify.app/java/types-and-values/c9fbb3b88b/