转载于:https://blog.csdn.net/ch999999999999999999/article/details/113151519
感谢作者:ch999999999999999999
Java 线上cpu占用过高分析
1、top 命令查看占用过高线程
9401 root 20 0 3163948 43592 11932 S 1.3 1.2 0:15.81 java
2609 polkitd 20 0 1333984 209256 11044 S 0.3 5.6 1:27.59 mysqld
13301 root 10 -10 145952 20784 5980 S 0.3 0.6 84:17.34 AliYunDun
23125 polkitd 20 0 1780292 514228 11512 S 0.3 13.8 19:45.03 mysqld
- 1
- 2
- 3
- 4
可以看出pid 为9401的线程占用过高
2、查看是哪个线程占用过高, 哪个线程耗费了多长时间
ps -mp 9401 -o THREAD,tid,time参数
// 参数解释
-m 显示所有的线程
-p pid 进程使用cpu的时间
-o 该参数是用户自定义格式
USER %CPU PRI SCNT WCHAN USER SYSTEM TID TIME
root 1.8 - - - - - - 00:00:20
root 0.0 19 - futex_ - - 9401 00:00:00
root 1.7 19 - n_tty_ - - 9402 00:00:19
root 0.0 19 - futex_ - - 9403 00:00:00
root 0.0 19 - futex_ - - 9404 00:00:00
root 0.0 19 - futex_ - - 9405 00:00:00
- 1
- 2
- 3
- 4
- 5
- 6
- 7
可以看出9402线程 占用过高
3、将线程id转换为16进制格式(英文字母小写格式) -> printf “%x\n” 有问题的线程id
printf "%x\n" 9402
- 1
结果: 24ba
4、jstack 进程ID|grep tid(16进制线程小写英文) -A60
jstack 9402 | grep 24ba -A60
- 1
结果:
"main" #1 prio=5 os_prio=0 tid=0x00007fc380009800 nid=0x2c84 runnable [0x00007fc387caa000]
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 <0x00000000c701b490> (a java.io.BufferedOutputStream)
at java.io.PrintStream.write(PrintStream.java:482)
- locked <0x00000000c7004fb0> (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 <0x00000000c7004f70> (a java.io.OutputStreamWriter)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
at java.io.PrintStream.newLine(PrintStream.java:546)
- eliminated <0x00000000c7004fb0> (a java.io.PrintStream)
at java.io.PrintStream.println(PrintStream.java:737)
- locked <0x00000000c7004fb0> (a java.io.PrintStream)
at TestJavaLinux.main(TestJavaLinux.java:11)
“VM Thread” os_prio=0 tid=0x00007fc380073000 nid=0x2c87 runnable
“GC task thread#0 (ParallelGC)” os_prio=0 tid=0x00007fc38001e800 nid=0x2c85 runnable
“GC task thread#1 (ParallelGC)” os_prio=0 tid=0x00007fc380020800 nid=0x2c86 runnable
“VM Periodic Task Thread” os_prio=0 tid=0x00007fc3800bf000 nid=0x2c8e waiting on condition
JNI global references: 5
- 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
由此可见是 at TestJavaLinux.main(TestJavaLinux.java:11) 我们的11行代码产出的原因
我们在代码里面写了死循环
5、注意:
注意:这里要使用程序启动的用户执行此命令
使用root会提示:
Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding