Thread problemsmedium3-5 years

`jcmd <pid> Thread.print` prints "Found one Java-level deadlock" with two threads, each shown as waiting on a lock the other holds. How does the JVM actually determine this is a deadlock rather than just two threads that happen to be blocked, and what can this detector not see?

The JVM isn't guessing from symptoms — it builds an actual graph. Every thread that's blocked waiting for a monitor is an edge pointing from that thread to whoever currently holds it; a thread that both holds one monitor and is waiting on another contributes a second edge. The detector walks this "wait-for" graph looking for a cycle — a path of waiting-for edges that loops back to where it started — and reports a deadlock exactly when it finds one, which is why the dump can name the exact threads and locks involved rather than just observing that things look stuck. What it can't see is anything that leaves the JVM: two separate processes each waiting on a lock the other holds, or two database transactions each waiting on a row the other has locked — those need their own detectors, which is why a database deadlock shows up as an exception the application catches, not a JVM-reported deadlock.

The lesson behind it →
More on Thread problems