java调试-jstack命令

jstack命令使用

jstack可用于导出java运用程序的线程堆栈,其基本使用语法为:

1
jstack [-l] pid

-l 打印关于锁的附加信息,例如属于java.util.concurrent的ownable synchronizers列表.

常用用法

下面这段代码运行之后会出现死锁现象(因为线程1持有lock1,在等待lock2,线程2持有lock2在等待lock1,造成了循环等待,形成死锁):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.zsr.test.lock;
/**
*
* Created by david.zhang
*/
public class TestDeadLock {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (lock2) {
System.out.println("线程1执行....");
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (lock1) {
System.out.println("线程2执行...");
}
}
}
});
t1.start();
t2.start();
}
}

运行这段代码,然后使用jstack命令导出这个程序的线程堆栈信息:

1
nalideMacBook-Pro-4:public nali$ jstack -l 35072 > /Users/nali/deadlock.txt

打开导出的线程堆栈信息文件,文件末尾如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Found one Java-level deadlock:
=============================
"Thread-1":
waiting to lock monitor 0x00007fe6d48432b8 (object 0x00000007d558e9d8, a java.lang.Object),
which is held by "Thread-0"
"Thread-0":
waiting to lock monitor 0x00007fe6d4844758 (object 0x00000007d558e9e8, a java.lang.Object),
which is held by "Thread-1"
Java stack information for the threads listed above:
===================================================
"Thread-1":
at com.zsr.test.lock.TestDeadLock$2.run(TestDeadLock.java:39)
- waiting to lock <0x00000007d558e9d8> (a java.lang.Object)
- locked <0x00000007d558e9e8> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:745)
"Thread-0":
at com.zsr.test.lock.TestDeadLock$1.run(TestDeadLock.java:23)
- waiting to lock <0x00000007d558e9e8> (a java.lang.Object)
- locked <0x00000007d558e9d8> (a java.lang.Object)
at java.lang.Thread.run(Thread.java:745)
Found 1 deadlock.

导出的线程堆栈文件中明确提示发现死锁,并且指明了死锁的原因。

jstack不仅能够导出线程堆栈,还能自动进行死锁检测,输出线程死锁原因。

热评文章