Video in progress

What is a deadlock, and how does it come about?

When two or more threads each wait for a lock held by the other and stand still forever, that is a deadlock. It usually appears when locks are acquired in different orders.

📖 Answer

The smallest example:

Object a = new Object(), b = new Object();

new Thread(() -> {
    synchronized (a) {
        sleepQuietly(50);
        synchronized (b) { System.out.println("1"); }
    }
}).start();

new Thread(() -> {
    synchronized (b) {
        sleepQuietly(50);
        synchronized (a) { System.out.println("2"); }
    }
}).start();

The first thread holds a and waits for b; the second does the opposite. Neither lets go, so the program hangs while CPU sits at zero.

Four conditions must hold together for a deadlock: the resource is exclusive, a thread holds one while requesting another, you can't forcibly take it away, and there is a circular wait. If you break any one of them, there is no deadlock.

In practice the easiest fix is to acquire locks in the same order everywhere (for example, by account ID, from smaller to larger). Another way is ReentrantLock.tryLock(timeout).

jstack <pid> finds a deadlock on its own and reports "Found one Java-level deadlock".