红联Linux门户
Linux帮助

java中在linux下利用jstack检测死锁

发布时间:2016-03-14 16:11:33来源:linux网站作者:Entropy_

首先,编写一个死锁程序:
package deadlock;
public class testJstack {
final static Object resource_1 = new Object();
final static Object resource_2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread("t1") {
public void run() {
synchronized (resource_1) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("locked resource_1");
synchronized (resource_2) {
System.out.println("thread t1 done.");
}
}
}
};
Thread t2 = new Thread("t2") {
public void run() {
synchronized (resource_2) {
System.out.println("locked resource_2");
synchronized (resource_1) {
System.out.println("thread t2 done.");
}
}
}
};
t1.start();
t2.start();
}
}


程序运行结果是:

lock resource_2
lock resource_1


接下来在终端中输入jsp查看当前运行的java程序:

7480 testJstack
13420 Jps


获取testJstack的进程ID为7480.然后使用命令:

jstack -l 7480 >deadlock.jstack


将jstack检测结果放入文件deadlock.jstack。使用vim查看该文件:

java.lang.Thread.State: RUNNABLE
Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE
java.lang.Thread.State: BLOCKED (on object monitor)
at testJstack$2.run(testJstack.java:29)
- waiting to lock <0x8c087670> (a java.lang.Object)
- locked <0x8c087678> (a java.lang.Object)
java.lang.Thread.State: BLOCKED (on object monitor)
at testJstack$1.run(testJstack.java:15)
Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE

Locked ownable synchronizers:
- None
java.lang.Thread.State: RUNNABLE

Locked ownable synchronizers:
java.lang.Thread.State: RUNNABLE
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- locked <0x8c050b30> (a java.lang.ref.ReferenceQueue$Lock)

Locked ownable synchronizers:
- None

- waiting on <0x8c050a30> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:485)
- locked <0x8c050a30> (a java.lang.ref.Reference$Lock)

Locked ownable synchronizers:
"VM Thread" prio=10 tid=0x0807e800 nid=0x260c runnable

JNI global references: 576

Found one Java-level deadlock:
=============================
"t2":
which is held by "t1"
"t1":
which is held by "t2"

Java stack information for the threads listed above:
===================================================
"t2":
at testJstack$2.run(testJstack.java:29)
- waiting to lock <0x8c087670> (a java.lang.Object)
- locked <0x8c087678> (a java.lang.Object)
"t1":
at testJstack$1.run(testJstack.java:15)
- waiting to lock <0x8c087678> (a java.lang.Object)
- locked <0x8c087670> (a java.lang.Object)

Found 1 deadlock.


本文永久更新地址:http://www.linuxdiyf.com/linux/18935.html