Scrivio Interview library
LeadershipAdvanced7 min read · updated 12 November 2026

Your platform's shared libraries contain many lazily initialised singletons, caches and registries written by different people. What rules for initialisation and publication would you set so that libraries are correct when used from many threads?

I would set a short set of rules: prefer eager initialisation or the holder-class idiom for static singletons, make shared objects immutable with final fields wherever possible, require every shared mutable field to document its guarding lock or its volatile publication, and forbid starting threads or registering callbacks in constructors. Then I would back the rules with review checklists, static analysis and concurrency tests for the core libraries, so they are enforced rather than remembered.

Why this question is asked

Shared platform libraries are used by every service, often from many threads at once, so their initialisation and publication code is some of the most concurrency-sensitive code in an organisation. When many people have written singletons, caches and registries over the years, each in their own style, some of them will be subtly wrong: a lazily created singleton visible half-built, a registry map updated without a lock, a listener registered before it is ready. Interviewers ask this leadership question to see whether a senior engineer can turn memory-model knowledge into a small set of rules that people can follow and reviewers can check. In this answer, we will look at the typical failures, set each rule with its reasoning, and then make the rules stick through tooling and review.

1The Failures We Want to Prevent

The bugs in such libraries tend to fall into a few families. Unsafe lazy initialisation: a static or instance field initialised on first use without volatile or a lock, so a thread can see a reference to an object whose fields are still defaults, the classic broken double-checked locking. Mutable shared state with no documented guard: a registry backed by a HashMap that is updated at runtime from several threads. Escaping this: a constructor that registers the object with an event bus or starts a background thread, which can then use the object before construction ends.

What these share is that they work in tests and fail rarely in production, often only under load or on ARM hardware, whose weaker memory ordering exposes races that x86 hides. So the rules must prevent the patterns rather than rely on catching the failures.

2Rule 1: Static Singletons Are Eager or Use a Holder Class

For static singletons, the safest options use the JVM's own class initialisation, which runs under a lock and safely publishes whatever it creates.

Java
// Eager: simplest, correct, fine unless construction is expensive or may fail
public final class Metrics {
private static final Metrics INSTANCE = new Metrics();
public static Metrics get() { return INSTANCE; }
}
// Holder idiom: lazy, created on the first get(), no locking on later calls
public final class Codecs {
private static final class Holder {
static final Codecs INSTANCE = new Codecs(); // runs when Holder is first used
}
public static Codecs get() { return Holder.INSTANCE; }
}

Hand-written double-checked locking is allowed only for instance fields where these idioms cannot apply, and then only with a volatile field and the standard local-variable form. Making this the rule removes the most common broken pattern in one step, and it is easy to check in review.

3Rule 2: Shared Objects Are Immutable Where Possible

An immutable object with all fields final, built in its constructor without letting this escape, can be shared freely: the final field guarantee means any thread that sees the reference sees the constructor's values, even if the reference was published carelessly. Records give this almost for free, as long as their components are themselves immutable, so lists and maps are copied with List.copyOf and Map.copyOf in the compact constructor.

For state that must change, such as a registry or a cache, the preferred shape is an immutable snapshot behind a single volatile reference or AtomicReference, replaced as a whole, or a concurrent collection such as ConcurrentHashMap holding immutable values. These designs need almost no reasoning from the next person who touches them.

4Rule 3: Every Shared Mutable Field Documents Its Guard

Where mutable shared state remains, the rule is that every field accessed by more than one thread states how it is protected: which lock guards it, or that it is volatile and what it publishes, or that it is confined to one thread. The annotations from the Java Concurrency in Practice tradition, such as @GuardedBy("lock") and @ThreadSafe, are a convenient way to write this, and some static analysis tools can check @GuardedBy; check which annotation library and checker your build supports.

Java
@ThreadSafe
public final class Registry {
private final Object lock = new Object();
@GuardedBy("lock")
private final Map<String, Handler> handlers = new HashMap<>();
private volatile Snapshot snapshot = Snapshot.EMPTY; // published copy for lock-free readers
public void register(String name, Handler h) {
synchronized (lock) {
handlers.put(name, h);
snapshot = new Snapshot(Map.copyOf(handlers)); // republish under the lock
}
}
public Handler find(String name) { return snapshot.handlers().get(name); } // no lock
}

The documentation does two jobs. It forces the author to decide the guard explicitly, which often reveals a missing one. And it gives reviewers something to check: every access to handlers must be inside synchronized (lock).

5Rule 4: Constructors Do Not Start Threads or Register Callbacks

A constructor that registers this with an event source, schedules a task that refers to this, or starts a thread lets the object escape before it is fully built, and then even the final field guarantee does not apply. The rule is that constructors only construct. Starting and registering happen in a separate step: a static factory that constructs then registers, an explicit start() method, or, in Spring, lifecycle callbacks such as SmartLifecycle.start() that run after the bean is fully wired.

6Making the Rules Stick

Rules that live only in a wiki fade. I would enforce them at three levels, from cheapest to most thorough.

Step throughHow the rules are enforced
  1. Written rulesfour rules with examples and the reasoning
  2. Review checklistinit idiom, immutability, documented guard, no escape
  3. Static analysis in CISpotBugs, Error Prone @GuardedBy, ArchUnit
  4. Concurrency testsstress tests and jcstress on x86 and ARM

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

The checklist keeps human review focused on the four rules. Static analysis catches the mechanical cases: SpotBugs has detectors for inconsistent synchronization and unsafe lazy initialisation of static fields, Error Prone can check @GuardedBy, and ArchUnit can forbid, for example, Thread.start calls from constructors or mutable static fields in library packages. Concurrency tests, including jcstress for the smallest interactions in the most-used libraries, run in CI on both x86 and ARM. Existing code gets a baseline of current violations that shrinks over time, ordered by how widely each library is used.

7Follow-up questions

Why not require everything to be synchronized and be done?

Locking everything is safe for visibility but slow on hot paths, prone to deadlocks when locks nest across libraries, and still does not fix escaping this. Immutable objects and single-reference snapshots are both faster and easier to reason about, so the rules steer people there first and use locks for genuinely mutable state.

How do you get teams to follow the rules?

Keep them few, explain why each exists with a real bug from our own code, give copyable examples for each, and make the tools do most of the checking. Reviewers then point to a rule and an example rather than arguing case by case. A short exception process keeps the rules from blocking legitimate special cases.

Where does Spring fit in for singletons?

Most singletons in a Spring application are beans, and the container creates and publishes them safely during startup, so the static singleton rules matter mainly for plain libraries used outside Spring. The other rules still apply to beans: mutable fields in a singleton bean that request threads change need a documented guard, and beans should register listeners or start threads from lifecycle callbacks, not constructors.

8Conclusion

In this answer, we set four rules for shared libraries: static singletons use eager initialisation or the holder-class idiom, shared objects are immutable with final fields where possible, every shared mutable field documents its lock or volatile publication, and constructors never start threads or register callbacks. We made the rules stick with a review checklist, static analysis such as SpotBugs, Error Prone and ArchUnit, and concurrency tests for core libraries run on both x86 and ARM.

What to say in the interviewAbout 100 seconds aloud

Open with

I would set a small number of rules that each prevent a family of bugs, and back them with tools. First, static singletons use eager initialisation, a static final field, or the holder-class idiom for laziness, because both use the JVM's class initialisation, which is locked and publishes safely.

Then, if they want more

Hand-written double-checked locking is only for instance fields, with volatile and the standard form. Second, shared objects should be immutable wherever possible: final fields, records with List.copyOf or Map.copyOf for their collections, and no escaping this, because then the final field guarantee makes them safe to share even if publication is careless.

For state that changes, prefer an immutable snapshot behind a volatile reference or AtomicReference, or a ConcurrentHashMap holding immutable values. Third, every shared mutable field must document how it is guarded, which lock with @GuardedBy, or that it is volatile and what it publishes. That forces the decision and gives reviewers something concrete to check.

Fourth, constructors only construct: no starting threads, no registering this as a listener, no scheduling tasks that capture this; that goes in a factory, a start method or a Spring lifecycle callback.

To make the rules stick, I would add them to the review checklist with examples from our own incidents, use static analysis in CI, like SpotBugs for unsafe lazy init and inconsistent synchronization, Error Prone for @GuardedBy and ArchUnit for constructor rules, keep a shrinking baseline for existing code, and require stress or jcstress tests for the core libraries on both x86 and ARM.

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
JLS chapter 17, Threads and Locks
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 "Your platform's shared libraries contain many lazily initialised singletons, caches and...": https://scrivio-interview-library.netlify.app/java/java-memory-model/e613230e76/