Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Thread 1 runs

Java
synchronized (a) {
synchronized (b) { ... }
}

and thread 2 runs

Java
synchronized (b) {
synchronized (a) { ... }
}

Explain why this can deadlock, how you would see it in a thread dump, and how to fix it.

Thread 1 can take the monitor of a and then wait for b, while thread 2 has taken b and waits for a; each holds what the other needs, so neither ever proceeds. A thread dump from jstack or jcmd Thread.print reports Found one Java-level deadlock and shows each thread BLOCKED, waiting to lock a monitor held by the other. We fix it by acquiring the locks in one consistent global order (always a before b), or by using tryLock with a timeout and backing off, or by reducing the two locks to one, and we avoid calling unknown code such as callbacks while holding a lock.

Why this question is asked

Nested synchronized blocks in opposite orders are the textbook deadlock, and they still appear in real code, usually not side by side as in this question but in two methods written months apart. Interviewers ask this to check three skills at once: whether we can see the interleaving that causes the hang, whether we can confirm it from a thread dump in production, and whether we know more than one fix. In this answer, we will recap what synchronized does, walk through the interleaving, read the thread dump, and then go through the fixes and the habit that prevents most of these bugs.

1A Quick Recap of synchronized

Every Java object has a monitor, an internal lock. A synchronized (x) block acquires x's monitor before running its body and releases it when the block exits, normally or by exception. Only one thread can hold a given monitor at a time; any other thread that reaches synchronized (x) is BLOCKED until the monitor is free. Monitors are reentrant, so a thread can re-enter a block on a monitor it already holds.

Nothing in that design notices if two threads wait for each other. A blocked thread simply waits, forever if necessary.

2Why the Two Orders Can Deadlock

Here is the code from the question, made runnable. A short sleep between the two locks makes the bad interleaving happen almost every time; without it, the deadlock is rare but still possible.

Java
Object a = new Object(), b = new Object();
Thread t1 = new Thread(() -> {
synchronized (a) { // t1 holds a
sleep(50);
synchronized (b) { // t1 waits for b, held by t2
System.out.println("t1 done"); // never printed
}
}
}, "worker-1");
Thread t2 = new Thread(() -> {
synchronized (b) { // t2 holds b
sleep(50);
synchronized (a) { // t2 waits for a, held by t1
System.out.println("t2 done"); // never printed
}
}
}, "worker-2");
t1.start(); t2.start(); // the program hangs; both threads are BLOCKED
Step throughThe interleaving that deadlocks
worker-1monitor amonitor bworker-2
lock a: acquired
lock b: acquired
lock b: BLOCKED, held by worker-2
lock a: BLOCKED, held by worker-1

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

After the fourth step no thread can move, and nothing will ever release the monitors.

The problem is the timing between the first and second lock. If t1 takes both locks before t2 starts, everything works, which is why such code passes tests. But if each thread takes its first lock before the other takes its second, we have all four deadlock conditions: exclusive monitors, each thread holding one while waiting for another, no way to take a monitor away, and a cycle of waits.

3Seeing It in a Thread Dump

In production we confirm the deadlock with a thread dump, taken with jstack <pid> or jcmd <pid> Thread.print. The JVM runs a deadlock check on monitors and java.util.concurrent locks and prints the result at the end of the dump.

Text
Found one Java-level deadlock:
=============================
"worker-1":
waiting to lock monitor 0x00007f8b2c00a2b8 (object 0x000000070fe1c6a8, a java.lang.Object),
which is held by "worker-2"
"worker-2":
waiting to lock monitor 0x00007f8b2c00c1d8 (object 0x000000070fe1c698, a java.lang.Object),
which is held by "worker-1"
Java stack information for the threads listed above:
"worker-1":
at Demo.lambda$main$0(Demo.java:9)
- waiting to lock <0x000000070fe1c6a8> (a java.lang.Object)
- locked <0x000000070fe1c698> (a java.lang.Object)

Notice how the dump gives us everything: each thread is BLOCKED, the object it waits for, the thread holding it, and the exact source lines of both the lock it holds and the lock it wants. That is usually enough to find the two code paths with opposite orders. Programmatically, ThreadMXBean.findDeadlockedThreads() returns the same information, which a health check can use to alert on it. The exact layout varies slightly between JDK versions.

4Fix 1: A Consistent Global Lock Order

The simplest and most common fix is to make every thread acquire the two locks in the same order. If both threads lock a before b, the second thread to arrive blocks on a while holding nothing, so it cannot be part of a cycle.

Java
// both threads
synchronized (a) {
synchronized (b) {
// work with both
}
}
// worker-2 now waits for a while holding nothing; when worker-1 finishes, worker-2 proceeds

When the locks are chosen at run time, as in a transfer between two accounts, we derive the order from data, for example by always locking the lower account id first. The rule should be written down next to the locks so that the next person who adds a nested lock follows it.

5Fix 2: tryLock With a Timeout, or Just One Lock

When a fixed order is impractical, a ReentrantLock lets a thread try to acquire the second lock with a timeout and, if it fails, release the first one, wait a random short time and start again. That breaks the hold-and-wait condition.

Java
boolean done = false;
while (!done) {
if (lockA.tryLock(50, TimeUnit.MILLISECONDS)) {
try {
if (lockB.tryLock(50, TimeUnit.MILLISECONDS)) {
try { work(); done = true; } finally { lockB.unlock(); }
}
} finally { lockA.unlock(); }
}
if (!done) Thread.sleep(ThreadLocalRandom.current().nextInt(10, 50)); // random backoff avoids livelock
}

It works, but it is more code and introduces retries, so I treat it as a fallback. Often the better question is whether we need two locks at all. If a and b always change together, one lock that protects both, or a single thread-safe object that owns both pieces of state, removes the problem entirely.

6Avoid Calling Unknown Code While Holding a Lock

Many real deadlocks do not look like this example, because the second lock is hidden. A method holds a lock and calls a listener, a callback, an overridden method or a library function, and that code takes another lock that some other thread holds in the opposite order. We cannot see the cycle by reading our own code. The habit that prevents this is to hold locks only around our own short critical section: copy the data we need under the lock, release it, and then call the outside code.

Java
List<Listener> copy;
synchronized (this) {
state = newState;
copy = List.copyOf(listeners); // take what we need under the lock
}
copy.forEach(l -> l.onChange(newState)); // call unknown code with no lock held

7Follow-up questions

Would virtual threads change anything here?

No. A deadlock is a cycle of waits, and it happens with any kind of thread. Virtual threads that deadlock on monitors simply stay blocked. On JDK 24 and later they also unmount from their carriers while blocked on a monitor, so other virtual threads keep running, but the two deadlocked tasks never finish.

Why does the deadlock not show up in unit tests?

Because it needs a specific interleaving: each thread must take its first lock before the other takes its second. In a fast test, one thread often finishes before the other starts. Stress tests with many iterations, or tools that inject delays between operations, make the window much more likely to hit.

How do I recover a deadlocked JVM?

There is no safe way to break a Java monitor deadlock from outside: the threads cannot be forced to release their monitors. The practical recovery is to restart the instance, after taking a thread dump for diagnosis, and then fix the code.

8Conclusion

In this answer, we saw that two threads taking the same two monitors in opposite orders can each hold one and wait for the other forever. A thread dump from jstack or jcmd Thread.print shows Found one Java-level deadlock with each thread waiting to lock a monitor held by the other, along with the source lines involved. The fix is a consistent global lock order, or tryLock with a timeout and random backoff, or collapsing the state under one lock, and the habit of never calling unknown code while holding a lock prevents most hidden versions of the same bug.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is the interleaving. Thread one takes the monitor of a and, before it gets to b, thread two takes the monitor of b. Now thread one waits for b, which thread two holds, and thread two waits for a, which thread one holds.

Then, if they want more

Monitors are exclusive, neither thread releases what it holds while waiting, and nothing can take a monitor away, so they wait forever. It only happens when the timing lines up, which is why it can pass tests and hang in production. To confirm it, I take a thread dump with jstack or jcmd Thread.print.

At the end it says Found one Java-level deadlock and lists each thread waiting to lock a monitor held by the other, and the stack traces show the lines with locked and waiting to lock, so I can find both code paths.

The main fix is a consistent global order: both threads lock a before b, so the second one waits while holding nothing. If the locks are chosen at run time, I derive the order from data, like the lower id first.

Alternatives are ReentrantLock.tryLock with a timeout, releasing and retrying with random backoff, or simply using one lock if a and b always change together. And as a habit, I never call callbacks or other unknown code while holding a lock, because that is how hidden lock cycles form.

About this answer

Last updated
12 November 2026
Versions it names
Java 24
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 "Thread 1 runs": https://scrivio-interview-library.netlify.app/java/concurrency-problems/e94cfade3c/