Scrivio Interview library
LeadershipPrincipal8 min read · updated 12 November 2026

Over 15 years your codebase has accumulated synchronized blocks, ReentrantLocks, ReadWriteLocks, StampedLocks and custom lock wrappers. What would you standardise or forbid in locking, and how do you weigh consistency against letting experts optimise?

I would standardise on designs that avoid shared mutable state first, then on synchronized and ReentrantLock as the two default primitives with written guidance on when each fits. ReadWriteLock and StampedLock would need a justification and a benchmark, custom lock wrappers would need expert review or be migrated away, and holding any lock across I/O or a remote call would be forbidden. Consistency is the default because most code is read and changed by non-experts for years; experts may optimise, but inside small, owned, documented exceptions, and the guidance is revisited as the JDK changes, as it did with virtual thread pinning in JDK 24.

Why this question is asked

A long-lived codebase collects every locking style its authors ever learned, and each style has its own failure modes. A reader who meets five kinds of lock in one module needs to know all five to change it safely. At the same time, a blanket rule can block a real optimisation that a specialist needs. Interviewers ask this to see how a technical leader balances those forces with a policy people will actually follow. In this answer, we will look at where the variety comes from and what it costs, then build the standard layer by layer: avoid locks where we can, defaults, justified exceptions, one firm prohibition, how to weigh consistency against expertise, and how to keep the guidance current.

1What the Variety Costs

Each locking primitive is reasonable on its own. synchronized is simple and always released. ReentrantLock adds timeouts, interruptible waits and conditions. ReadWriteLock lets readers share. StampedLock adds optimistic reads but is not reentrant. Custom wrappers often added logging or metrics years ago. The trouble is the combination: a method that takes a synchronized monitor, then calls a helper that takes a StampedLock, then a wrapper with its own lock, has a lock order nobody wrote down, and that is how deadlocks and stalls appear years later.

So the goal of a standard is not to pick the best primitive. It is to reduce the number of things a maintainer must understand, and to make the unusual cases visible.

2First Rule: Prefer Designs Without Shared Mutable State

The best lock is the one we do not need. Most locking in a business service protects state that could be designed away. Immutable objects, such as records with final fields, can be shared freely. Thread confinement keeps an object on one thread, like a request-scoped builder. Concurrent collections, such as ConcurrentHashMap with computeIfAbsent or merge, handle the common map-and-counter cases with locking that the JDK's experts already got right. And an immutable snapshot published through a volatile reference serves read-mostly data with no reader locks at all.

So the first question in a review is not 'which lock?' but 'why is this state shared and mutable?' That single question removes a large share of the locks in a typical service.

3Defaults: synchronized and ReentrantLock, With Guidance

For the locking that remains, two primitives cover almost everything, and the guidance on choosing between them fits in a paragraph. synchronized is the default, because the JVM always releases it and its scope is visible in the code. ReentrantLock is used when we need timed or interruptible acquisition, more than one condition, or fairness, and always with lock() immediately before try and unlock() in finally. Locks are private final fields, never public objects or strings.

Static analysis makes the guidance cheap to follow: rules that check unlock in finally, lock before try, and that flag locking on value-based classes. Rules that a build enforces are applied consistently; rules that live only in a wiki are not.

A tiered locking standard
TierConstructsWhat is required
Preferredimmutability, confinement, concurrent collectionsnothing special
Default lockssynchronized, ReentrantLockguidelines and static analysis
JustifiedReentrantReadWriteLock, StampedLockwritten reason, benchmark, owner
Expert onlycustom lock wrappers, lock-free code, VarHandleexpert review, tests, inventory entry
Forbiddenany lock held across I/O or remote callsno exceptions without architecture review
Each step down the table needs more justification.

4Justified Exceptions: ReadWriteLock, StampedLock and Custom Code

ReadWriteLock and StampedLock are performance tools, and performance tools should prove themselves. A read-write lock is often slower than a plain lock for short critical sections, because readers still update a shared counter, and in non-fair mode writers can wait a long time behind a stream of readers. StampedLock is fast for optimistic reads but not reentrant, so a call path that takes the write lock twice hangs. So both need a written reason and a benchmark with realistic read and write ratios and thread counts, compared against the simple version, plus a named owner.

Custom lock wrappers need the strongest treatment. Many were written to add timing or logging that JFR and modern profilers now provide, so the usual decision is to migrate them to the standard primitives. Any that stay need review by someone who knows the memory model, a stress test, and an entry in an inventory of unusual concurrency code.

5The One Firm Prohibition: No Locks Across I/O

Holding a lock while calling a database, another service or the file system means the lock's hold time is set by something we do not control. If the remote side slows from 5 ms to 2 seconds, every thread that needs the lock waits 2 seconds too, and a local slowdown becomes a service-wide outage. This is the most common way locking causes incidents, so it is the one rule I would make firm.

The fix is almost always to do the I/O outside the lock and use the lock only to read or publish the result, for example fetch the new data first and then swap a reference, or use a single-flight pattern so one thread fetches while others use the current value.

Java
// Forbidden: the lock's hold time depends on the remote call
synchronized (this) {
rates = ratesClient.fetchAll(); // 5 ms normally, seconds when the service is slow
}
// Allowed: remote call outside, lock only to publish (or a volatile field without any lock)
Map<String, BigDecimal> fresh = ratesClient.fetchAll();
synchronized (this) {
rates = fresh; // nanoseconds
}

6Weighing Consistency Against Letting Experts Optimise

Consistency wins by default, because of who reads the code. Over ten or fifteen years, most changes to a class will be made by people who did not write it and are not concurrency specialists. Each unusual construct raises the chance that one of them changes it incorrectly, and concurrency bugs are expensive: rare, hard to reproduce and often in production. A small speedup rarely pays for that.

But a rigid rule has a cost too. There are hot paths, a pricing cache serving millions of reads per second, where a StampedLock or a lock-free structure is worth real money. So the policy allows experts to optimise inside a box: the code is encapsulated in a small component with a simple API, it has a named owner and a benchmark that justifies it, it has a documented fallback to the simple version, and the rest of the codebase never sees the sharp edges. The decision is made on measured service-level benefit, not on a microbenchmark alone.

Step throughApproving a non-default lock
  1. Can the design avoid shared mutable state?
    YesDo that insteadNoContinue
  2. Do synchronized or ReentrantLock meet the need?
    YesUse the defaultNoContinue
  3. Benchmark shows a service-level gain?
    YesContinueNoReject
  4. Encapsulate, name an owner, document the fallbackadd it to the inventory

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

7Revisiting the Guidance as the JDK Changes

Locking advice depends on the JDK, so the standard needs a review date. The clearest recent example is virtual threads. On Java 21 to 23, a virtual thread blocking inside synchronized pinned its carrier thread, so teams were told to prefer ReentrantLock around blocking code. JEP 491 in JDK 24 removed most of that pinning, so on Java 25 the advice moves back to synchronized as the simple default. A standard written in 2023 and never revisited would now push people towards the more error-prone choice for no reason.

So I would review the guidance with each LTS upgrade, check the inventory of exceptions at the same time, and record the reason behind every rule, so that when the reason disappears, the rule can go too.

8Follow-up questions

How do you introduce this standard without rewriting the whole codebase?

Apply it to new code and to code being changed anyway, enforce the checkable parts in the build with a baseline for existing violations, and make a short list of high-risk spots, such as locks held across I/O, to fix deliberately. A big rewrite of working locking code carries more risk than it removes.

Who counts as an expert for reviewing custom locking code?

Someone who can explain the happens-before edges the code relies on, can write a stress test such as a jcstress case for it, and is accountable for it. In a large organisation that is usually a small named group, and their review is a required step for the expert tier.

Is it ever acceptable to hold a lock during I/O?

Occasionally, for example writing to a local file that must not be interleaved, where the hold time is short and bounded. That is why the prohibition allows an architecture-reviewed exception. Remote calls are the case I would almost never accept, because their latency is outside our control.

9Conclusion

In this answer, we saw that a codebase with many locking styles is costly because maintainers must understand every one and their interactions. The standard starts by avoiding shared mutable state, makes synchronized and ReentrantLock the defaults with guidance and static analysis, requires a reason and a benchmark for ReadWriteLock and StampedLock, sends custom wrappers to expert review or migration, and forbids holding locks across I/O and remote calls. Consistency is the default because most future maintainers are not specialists, experts optimise inside small owned components with a fallback, and the guidance is revisited with each JDK change, such as the JDK 24 pinning fix.

What to say in the interviewAbout 80 seconds aloud

Open with

I would start by reducing the need for locks at all: immutable data, thread confinement, concurrent collections, and immutable snapshots behind a volatile reference cover most of what a business service needs.

Then, if they want more

For the rest, synchronized is the default and ReentrantLock is used when we need tryLock, interruptible waits, several conditions or fairness, with the lock-before-try pattern enforced by static analysis. ReadWriteLock and StampedLock are performance tools, so they need a written reason, a benchmark with realistic read and write ratios, and an owner.

Custom lock wrappers go to expert review, and most of them get migrated to the standard primitives. The one firm rule is no lock held across I/O or remote calls, because then a slow dependency turns into a service-wide stall.

On consistency versus expertise: I default to consistency, because over fifteen years most people changing this code are not concurrency specialists, and concurrency bugs are rare and expensive. But I let experts optimise inside a box: a small encapsulated component, a benchmark showing a service-level gain, a named owner and a documented fallback.

And I revisit the guidance with JDK upgrades; for example after JEP 491 in JDK 24, the advice to prefer ReentrantLock for virtual threads no longer holds, so the standard should change with it.

About this answer

Last updated
12 November 2026
Versions it names
Java 24, Java 21, 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 "Over 15 years your codebase has accumulated synchronized blocks, ReentrantLocks...": https://scrivio-interview-library.netlify.app/java/locks/4b9e4b09ec/