Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Classes in your shared libraries declare public synchronized methods, and some client code synchronizes on library objects for its own purposes, causing unexpected blocking and one deadlock. Write the locking guidelines for public library classes.

The guidelines would say: public library classes lock on private final lock objects, never on this or on the Class object, so client code cannot interfere with internal locking. Every public class documents its thread safety level: immutable, thread-safe, conditionally thread-safe, or not thread-safe. Internal locks are never held while calling client callbacks or other unknown code, locking stays an implementation detail that can change without breaking clients, and all of this goes into the library review checklist.

Why this question is asked

A shared library is used by dozens of teams who cannot see its internals, and its locking becomes part of their programs whether we intend it or not. When a library uses public synchronized methods, its lock is the object itself, which every client holds a reference to. Client code that synchronizes on that object for its own reasons joins the library's lock without knowing it, and that is how unexpected blocking and deadlocks between unrelated code appear. Interviewers ask this to see whether we can turn that experience into clear rules. In this answer, we will reproduce how the incident happened, then go through each guideline with the reason behind it, and finish with how to put the rules into the review process.

1How Client Code Ends Up Inside the Library's Lock

A public synchronized method locks this. If a client also writes synchronized (registry) { ... } to make a few calls atomic, it uses the very same monitor. That is sometimes intended, as with the documented client-side locking of Collections.synchronizedList, but in our incident the client was simply using the library object as a convenient lock for its own unrelated state.

Now two components share one lock without knowing it. The client holds the registry's monitor while waiting for something slow, and every library call from other threads blocks. Worse, suppose a client thread holds its own cache lock and calls registry.register(), which needs the registry's monitor, while a library thread is inside fire(), holding that monitor, and calls back into a client listener that needs the cache lock. Each thread holds the lock the other wants, in opposite order, and that is a lock-order deadlock.

Java
public class Registry { // library
private final Map<String, Listener> listeners = new HashMap<>();
public synchronized void register(String k, Listener l) { listeners.put(k, l); }
public synchronized void fire(String k) { listeners.get(k).onEvent(); } // callback under lock
}
// client code
synchronized (registry) { ... slow work ... } // same monitor: every library call now waits
synchronized (clientCache) { // client thread: clientCache, then registry
registry.register("k", listener);
}
// library thread in fire(): registry, then the listener locks clientCache -> deadlock
Step throughThe deadlock between client and library
Client threadregistry monitorclientCache lockLibrary thread
fire(): holds registry
holds clientCache
callback onEvent() wants clientCache: waits
register() wants registry: waits

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

Each thread holds one lock and waits for the other's. Neither can proceed.

2Guideline 1: Lock on Private Final Objects

Inside the library, every lock is a private final object that no client can reach. Then client code can synchronize on our object as much as it likes without affecting us, and we can reason about every place our lock is used, because they are all in our own class.

Java
public final class Registry {
private final Object lock = new Object(); // nobody outside can lock this
private final Map<String, Listener> listeners = new HashMap<>();
public void register(String k, Listener l) {
synchronized (lock) { listeners.put(k, l); }
}
}

The same applies to static state: a private static final Object rather than static synchronized methods, which lock the public Class object. Concurrent collections or atomic classes are even better where they fit, since they need no lock of ours at all.

3Guideline 2: Document the Thread Safety Level of Every Public Class

Clients need to know how they may use a class from several threads, and guessing from the presence of synchronized is exactly how they got it wrong. So every public class states one of a few standard levels in its Javadoc, and optionally with an annotation such as @ThreadSafe or @Immutable from a shared annotations library.

Thread safety levels for the library's Javadoc
LevelMeaning for the caller
Immutablestate never changes; share freely
Thread-safeany method from any thread; no external locking needed
Conditionally thread-safesome sequences need external locking; doc names the lock
Not thread-safecaller must confine it to one thread or lock around it
Conditionally thread-safe is the only level where clients are told to lock, and on what.

4Guideline 3: Never Call Unknown Code While Holding a Lock

The deadlock in our incident needed a callback under the lock. A listener, a user-supplied comparator, a lambda passed in by the client, or an overridable method are all code we do not control: it may take its own locks, block on I/O, or call back into our library. Holding our lock while running it creates lock orderings we cannot see.

The fix is to copy what we need while holding the lock, release it, and then call the foreign code. For listeners, a CopyOnWriteArrayList removes the lock from firing entirely.

Java
public void fire(String k) {
Listener l;
synchronized (lock) { l = listeners.get(k); } // hold the lock only to read
if (l != null) l.onEvent(); // call client code with no lock held
}

5Guideline 4: Keep Locking an Implementation Detail

Once clients can see or depend on our lock, we can never change it. If version 1 locks this and a client relies on that for atomic sequences, switching to a ReentrantLock or a concurrent map in version 2 silently breaks the client. With private locks and a documented thread safety level, the contract is the level, not the mechanism, so we are free to change the internals.

Where clients really need atomic compound operations, we provide them as methods, such as putIfAbsent or computeIfAbsent, rather than asking clients to lock our object.

6Putting the Rules Into Review

Guidelines only work if they are checked. The library review checklist gains a few questions: does any public class use synchronized methods or lock on this or a Class object; does every public class state its thread safety level; is any callback, listener or overridable method invoked under a lock; are compound operations offered as methods. Static analysis helps with the first: Error Prone's @GuardedBy checking and Sonar rules can flag synchronized methods and missing guards.

For existing classes, we fix the classes involved in the incident first, release the change in a minor version with a note that clients must not rely on locking the object, and work through the rest by usage.

7Follow-up questions

Is it ever right for a library to let clients lock its objects?

Yes, when it is deliberate and documented, as with conditionally thread-safe wrappers such as Collections.synchronizedList, where iteration must be done while holding the list's lock. In that case the lock is part of the public contract and must never change, so we should choose it rarely.

Why not just use ReentrantLock everywhere?

A private ReentrantLock is also fine, and adds tryLock, timeouts and multiple conditions. The point of the guideline is that the lock is private, not which kind it is. For simple cases a private Object with synchronized is shorter and cannot be left locked by a missing finally.

How would you handle the client team whose code caused the deadlock?

Without blame: the library made it possible by exposing its monitor. We fix the library so it no longer matters, and help the client team move their own locking to their own lock objects, explaining why sharing a monitor with a library is risky.

8Conclusion

In this answer, we saw how public synchronized methods let client code share a library's lock, and how a callback under that lock produced a deadlock. The guidelines are to lock on private final objects, to document every public class's thread safety level, to never call client or unknown code while holding an internal lock, to keep locking an implementation detail and offer compound operations as methods, and to add these checks to the library review checklist with tool support.

What to say in the interviewAbout 80 seconds aloud

Open with

The root problem is that a public synchronized method locks this, and every client has a reference to this, so client code that synchronizes on our object for its own reasons shares our lock.

Then, if they want more

In our incident that caused blocking, and the deadlock came from a callback: the library held its monitor while calling a listener that took a client lock, while a client thread held that lock and called into the library. So my first rule is that library classes lock on private final lock objects, never on this or on the class.

Second, every public class documents its thread safety level, immutable, thread-safe, conditionally thread-safe, naming the lock if clients must use one, or not thread-safe, so clients do not guess. Third, we never call callbacks, listeners or any code we do not own while holding an internal lock: copy what we need under the lock, release, then call out.

Fourth, locking is an implementation detail; if clients need atomic compound operations, we offer them as methods like putIfAbsent, so we can change the locking later without breaking anyone. Finally, I would add these points to the library review checklist and turn on Error Prone or Sonar rules, and fix the classes from the incident first.

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 "Classes in your shared libraries declare public synchronized methods, and some client...": https://scrivio-interview-library.netlify.app/java/synchronization/769a541453/