用于快速排查Java
的CPU
性能问题(top us
值过高),自动查出运行的Java
进程中消耗CPU
多的线程,并打印出其线程栈,从而确定导致性能问题的方法调用。
目前只支持Linux
。原因是Mac
、Windows
的ps
命令不支持列出线程线程,更多信息参见#33,欢迎提供解法。
PS,如何操作可以参见@bluedavy的《分布式Java应用》的【5.1.1 cpu消耗分析】一节,说得很详细:
top
命令找出有问题Java
进程及线程id
:- 开启线程显示模式
- 按
CPU
使用率排序 - 记下
Java
进程id
及其CPU
高的线程id
- 用进程
id
作为参数,jstack
有问题的Java
进程 - 手动转换线程
id
成十六进制(可以用printf %x 1234
) - 查找十六进制的线程
id
(可以用grep
) - 查看对应的线程栈
查问题时,会要多次这样操作以确定问题,上面过程太繁琐太慢了。
用法
show-busy-java-threads.sh # 从所有运行的Java进程中找出最消耗CPU的线程(缺省5个),打印出其线程栈 # 缺省会自动从所有的Java进程中找出最消耗CPU的线程,这样用更方便 # 当然你可以手动指定要分析的Java进程Id,以保证只会显示出那个你关心的Java进程的信息 show-busy-java-threads.sh -p <指定的Java进程Id> show-busy-java-threads.sh -c <要显示的线程栈数> show-busy-java-threads.sh <重复执行的间隔秒数> [<重复执行的次数>] # 多次执行;这2个参数的使用方式类似vmstat命令 show-busy-java-threads.sh -a <输出记录到的文件> # 记录到文件以方便回溯查看 ############################## # 注意: ############################## # 如果Java进程的用户 与 执行脚本的当前用户 不同,则jstack不了这个Java进程 # 为了能切换到Java进程的用户,需要加sudo来执行,即可以解决: sudo show-busy-java-threads.sh show-busy-java-threads.sh -s <指定jstack命令的全路径> # 对于sudo方式的运行,JAVA_HOME环境变量不能传递给root, # 而root用户往往没有配置JAVA_HOME且不方便配置, # 显式指定jstack命令的路径就反而显得更方便了 # -m选项:执行jstack命令时加上-m选项,显示上Native的栈帧,一般应用排查不需要使用 show-busy-java-threads.sh -m # -l选项:执行jstack命令时加上 -l 选项,显示上更多相关锁的信息,一般情况不需要使用 # 注意:和 -m -F 选项一起使用时,可能会大大增加jstack操作的耗时 show-busy-java-threads.sh -l # -F选项:执行jstack命令时加上 -F 选项(如果直接jstack无响应时,用于强制jstack),一般情况不需要使用 show-busy-java-threads.sh -F # 帮助信息 $ show-busy-java-threads.sh -h Usage: show-busy-java-threads.sh [OPTION]... [delay [count]] Find out the highest cpu consumed threads of java, and print the stack of these threads. Example: show-busy-java-threads.sh # show busy java threads info show-busy-java-threads.sh 1 # update every 1 seconds, (stop by eg: CTRL+C) show-busy-java-threads.sh 3 10 # update every 3 seconds, update 10 times Options: -p, --pid <java pid> find out the highest cpu consumed threads from the specifed java process, default from all java process. -c, --count <num> set the thread count to show, default is 5 -a, --append-file <file> specify the file to append output as log -s, --jstack-path <path> specify the path of jstack command -F, --force set jstack to force a thread dump use when jstack <pid> does not respond (process is hung) -m, --mix-native-frames set jstack to print both java and native frames (mixed mode) -l, --lock-info set jstack with long listing. Prints additional information about locks -h, --help display this help and exit delay the delay between updates in seconds count the number of updates delay/count arguments imitates style of vmstat command