0. 必须在java进程的用户下执行

a). 先排查自己业务代码,再第三方的开源代码
b). 工具类都在jdk/bin目录下, 实现代码在tools.jar中

1. jstack-线程快照-死锁/阻塞

ps aux | grep tomcat
./jstack 2129

1.1 线程状态--死锁和阻塞

//在java.lang.Thread.State中定义
NEW 线程创建未启动
RUNNABLE 正常运行中
TERMINATED 线程已执行完毕
TIMED_WAITING 这个状态就是有限的(时间限制)的WAITING, 一般出现在调用wait(long), join(long)等情况下, 另外一个线程sleep后, 也会进入TIMED_WAITING状态 BLOCKED 线程在等待进入临界区(Synchronized) //重点关注
WAITTING 这个状态下是指线程拥有了某个锁之后, 调用了他的wait方法, 等待其他线程/锁拥有者调用 notify / notifyAll 一遍该线程可以继续下一步操作;
线程调用了join方法 join了另外的线程的时候, 也会进入WAITING状态, 等待被他join的线程执行结束

[2.死循环定位]

2.1使用jstack定位

a). 先top定位消耗CPU最高的进程
b). top -Hp 12862 //查看进程下哪个线程占用资源最多
c). 定位到12907这个线程 把它转化成16进制是 326b
d). 用 jstack -l 12862 > jstack.log; 生成线程堆栈日志文件
e). 打开jstack.log文件 搜索0x326b
"pool-3-thread-2" prio=10 tid=0x00007fb780235000 nid=0x326b runnable [0x00007fb7c89c2000]
java.lang.Thread.State: RUNNABLE
at com.elasticsearch.river.kafka.KafkaRiver$UpLoadFileWorker.run(KafkaRiver.java:303)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744) Locked ownable synchronizers:
- <0x00000000f04077f8> (a java.util.concurrent.ThreadPoolExecutor$Worker) 定位到死循环的代码块,原因是没有sleep....
//示例代码
public class CpuTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
while (true) {
System.out.println("asdasdasd");
}
}
} "main" #1 prio=5 os_prio=0 tid=0x000000000060a000 nid=0x6614 runnable [0x00007f1879e43000]
java.lang.Thread.State: RUNNABLE
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:326)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
- locked <0x0000000084e150d8> (a java.io.BufferedOutputStream)
at java.io.PrintStream.write(PrintStream.java:482)
- locked <0x0000000084e032b0> (a java.io.PrintStream)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
- locked <0x0000000084e03268> (a java.io.OutputStreamWriter)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.newLine(PrintStream.java:546)
- eliminated <0x0000000084e032b0> (a java.io.PrintStream)
at java.io.PrintStream.println(PrintStream.java:807)
- locked <0x0000000084e032b0> (a java.io.PrintStream)
at CpuTest.main(CpuTest.java:8) Locked ownable synchronizers:
- None

3.内存泄漏定位

05-08 08:42