Java Concurrency Interview

Deadlock, livelock and diagnostics question 147 of 180 junior

What is a deadlock, and why does it not resolve itself?

The smallest example is two threads taking the same two locks in opposite order:

Object a = new Object(), b = new Object();
new Thread(() -> { synchronized (a) { pause(); synchronized (b) { } } }).start();
new Thread(() -> { synchronized (b) { pause(); synchronized (a) { } } }).start();

Each holds one lock and waits for the other. synchronized has no timeout and cannot be interrupted, and the JVM does not break deadlocks. A database picks a victim and rolls it back; the JVM just leaves both threads blocked, forever, with zero CPU.

That is also how it looks from outside: the service stops answering but is not busy. A thread dump (jstack <pid>) says it directly, with a section titled "Found one Java-level deadlock" that names the threads and the locks.

The fixes follow from the example: always take locks in one global order, hold as few as possible at once, or use ReentrantLock.tryLock with a timeout so a thread can back off instead of waiting forever.

deadlock basics

Quiz yourself on Deadlock, livelock and diagnostics Suggest a correction