昨天看到有人问:”一个程序在运行的时候,如何知道它是否发生死锁,如果发生死锁,如何找到发生死锁的位置?“;便贴了一段dump线程的数据,今天又有人问我怎么从dump文件中分析死锁,随做此文:
1、首先构造死锁,代码如下:
public class Deadlocker {
private static Object lock_1 = new int[1];
private static Object lock_2 = new int[1];
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("thread 1 start");
synchronized (lock_1) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread 1 get lock 1 need lock 2");
synchronized (lock_2) {
}
}
System.out.println("thread 1 end");
}
}
public class Thread2 extends Thread {
@Override
public void run() {
System.out.println("thread 2 start");
synchronized (lock_2) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread 2 get lock 2 need lock 1");
synchronized (lock_1) {
}
}
System.out.println("thread 2 end");
}
}
public static void main(String[] args) {
Thread1 thread1 = new Deadlocker().new Thread1();
Thread2 thread2 = new Deadlocker().new Thread2();
thread1.start();
thread2.start();
}
}
2 运行结果如下:
thread 1 start
thread 2 start
thread 1 get lock 1 need lock 2
thread 2 get lock 2 need lock 1
3、分析:
从打印的结果很容易分析线程1 和线程2 处于死锁。相互需要对方的持有的锁;
4、使用:jps 查看线程id,再使用:jstack 线程id > dumpthread 命令。部分结果如下(去除各种gc线程。。。):
第一部分:
“Thread-1” prio=10 tid=0x0000000040a49800 nid=0x2d1e waiting for monitor entry [0x00007f50eda98000]
java.lang.Thread.State: BLOCKED (on object monitor)
at Deadlocker$Thread2.run(Deadlocker.java:47)
– waiting to lock <0x00000007d6f97ec8> (a [I)
– locked <0x00000007d6f97ee0> (a [I)
“Thread-0” prio=10 tid=0x0000000040a47800 nid=0x2d1d waiting for monitor entry [0x00007f50edb99000]
java.lang.Thread.State: BLOCKED (on object monitor)
at Deadlocker$Thread1.run(Deadlocker.java:28)
– waiting to lock <0x00000007d6f97ee0> (a [I)
– locked <0x00000007d6f97ec8> (a [I)
。。。。。各种其他线程
这里可以看出两个线程处于BLOCKED 状态,各自在等待各自的锁( 0x00000007d6f97ec8 和0x00000007d6f97ee0 )
第二部分:
Found one Java-level deadlock:
“Thread-1”:
waiting to lock monitor 0x0000000040a33dd8 (object 0x00000007d6f97ec8, a [I),
which is held by “Thread-0”
“Thread-0”:
waiting to lock monitor 0x0000000040a365e0 (object 0x00000007d6f97ee0, a [I),
which is held by “Thread-1”
这个一看就更明白了。。说发现一个java死锁,Thread-1在等待一个lock,而这个锁被Thread-0 持有,
而 Thread-0在等待另外一个lock,而这个锁被Thread-1 持有
Java stack information for the threads listed above:
“Thread-1”:
at Deadlocker Thread2.run(Deadlocker.java:47)−waitingtolock<0x00000007d6f97ec8>(a[I)−locked<0x00000007d6f97ee0>(a[I)“Thread−0”:atDeadlocker Thread1.run(Deadlocker.java:28)
– waiting to lock <0x00000007d6f97ee0> (a [I)
– locked <0x00000007d6f97ec8> (a [I)
Found 1 deadlock.
上面的红色部分便也可以清楚查询到死锁的位置了;
当然据说第二部分只有java5 以上版本才有的(未验证)。