Detecting Deadlock: Thread Dumps and jstack
You'll learn how to use JVM diagnostic tools to identify and investigate deadlocks in running Java applications.
Understanding Thread Dumps
When your application freezes or hangs, the culprit is often deadlock. A thread dump is a snapshot of all threads in your JVM at a specific moment, showing what each thread is doing and which locks it holds or waits for. Think of it as a crime scene photograph—it captures the exact state when things went wrong.
Using jstack to Generate Thread Dumps
The jstack tool ships with the JDK and produces thread dumps for any running Java process:
jstack <process-id>
First, find your Java process ID using jps (Java Process Status):
jps
Then run jstack on that PID to get a detailed thread dump printed to your console.
Reading Deadlock Detection Output
The JVM's thread dump analysis automatically detects deadlocks. When present, you'll see a section like:
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x00007f8... (object 0x000000076...)
which is held by "Thread-2"
"Thread-2":
waiting to lock monitor 0x00007f9... (object 0x000000077...)
which is held by "Thread-1"
This clearly identifies the circular wait: Thread-1 waits for Thread-2's lock, while Thread-2 waits for Thread-1's lock.
Interpreting Thread States
Each thread entry shows its state (BLOCKED, WAITING, RUNNABLE), the lock it's trying to acquire, and which thread currently holds that lock. Look for BLOCKED threads in circular dependencies.
Key Takeaway:
Use jstack <pid> to generate thread dumps of running applications; the JVM automatically detects and reports deadlocks, showing you exactly which threads are stuck waiting for each other's locks.