Java死锁检查,使用jstack工具 jstack是java虚拟机自带的一种堆栈跟踪工具。 死锁代码 直接运行就会出现死锁,原因是因为加锁顺序不一致会导致死锁 public class DeadLockSample extends Thread { priv
Java死锁检查,使用jstack工具
jstack是java虚拟机自带的一种堆栈跟踪工具。
死锁代码
直接运行就会出现死锁,原因是因为加锁顺序不一致会导致死锁
public class DeadLockSample extends Thread {private String frs;
private String second;
public DeadLockSample(String name, String frs, String second) {
super(name);
this.frs = frs;
this.second = second;
}
public void run() {
synchronized (frs) {
System.out.println(this.getName() + " obtained: " + frs);
try {
Thread.sleep(1000L);
synchronized (second) {
System.out.println(this.getName() + " obtained: " + second);
}
} catch (InterruptedException e) {
// Do nothing
}
}
}
public static void main(String[] args) throws InterruptedException {
String lockA = "lockA";
String lockB = "lockB";
// 因为加锁顺序不一致会导致死锁
DeadLockSample t1 = new DeadLockSample("Thread1", lockA, lockB);
DeadLockSample t2 = new DeadLockSample("Thread2", lockB, lockA);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
开始排查
记录Java程序的PID
把这些程序的pid记录下来.
使用jstack工具
在jdk的bin目录下面用cmd执行命令 jstack PID
20216 是pid
cmd窗口执行:
D:\jdk\jdk1.8.0_172\bin>jstack 20216如果不是这个PID就尝试别的java.exe进程的pid试试.仔细观察输出日志
死锁日志
查找日志 ,找到处于BLOCKED状态的线程,这里处于BLOCKED状态线程的日志我没有粘贴到这里, 自己在操作的时候用工具在日志搜索 “BLOCKED” 关键字就能搜索到.
Found one Java-level deadlock:=============================
"Thread2":
waiting to lock monitor 0x00000000246f5088 (object 0x00000007412fd740, a java.lang.String),
which is held by "Thread1"
"Thread1":
waiting to lock monitor 0x00000000246f3d48 (object 0x00000007412fd778, a java.lang.String),
which is held by "Thread2"
Java stack information for the threads listed above:
===================================================
"Thread2":
at die.DeadLockSample.run(DeadLockSample.java:20)
- waiting to lock <0x00000007412fd740> (a java.lang.String)
- locked <0x00000007412fd778> (a java.lang.String)
"Thread1":
at die.DeadLockSample.run(DeadLockSample.java:20)
- waiting to lock <0x00000007412fd778> (a java.lang.String)
- locked <0x00000007412fd740> (a java.lang.String)
Found 1 deadlock.
上面日志明显说明是:
Thread1线程在 die.DeadLockSample.run(DeadLockSample.java:20)
Thread2 线程在 at die.DeadLockSample.run(DeadLockSample.java:20)
产生死锁了.
定位代码
找到上面指定Java类的指定行数,自己仔细想想是什么情况产生了死锁.剩下的就自己去改代码