Java CPU性能分析工具代码实例
这篇文章主要介绍了JavaCPU性能分析工具代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
背景
有处理过生产问题的同学基本都能遇到系统忽然缓慢,CPU突然飙升,甚至整个应用请求不可用。当出现这种情况下,在不影响数据准确性的前提下,我们应该尽快导出jstack和内存信息,然后重启系统,尽快回复系统的可用性,避免用户体验过差。本文针对CPU飙升问题,提供该问题的排查思路,从而能够快速定位到某线程甚至某快代码导致CPU飙升,从而提供处理该问题的思路。
排查过程
- 通过top命令查看cpu飙升的java进程pid
- 通过ps-mp[pid]-oTHREAD,tid,time查看该进程下所拥有的线程及各个线程占用cpu的使用率,并且记录CPU使用率过高的线程ID号
- 将线程ID号转换为16进程的数值记为tid_hex
- 使用jdk自带jstack监控命令
- 使用命令jstack[pid]|greptid_hex-A100命令输出该线程的堆栈信息
- 根据堆栈信息分析代码。
通过以上步骤可以查找出导致cpu飙升的相关代码位置,然后对代码进行codereview即可。
工具封装
以上步骤已经封装为脚本文件,通过以下脚本文件只需要指定进程ID即pid即可导出默认前5条导致CPU率过高的堆栈信息。
已上传github:点我进入
./java-thread-top.sh-ppid
#!/bin/bash
#@Function
#Findoutthehighestcpuconsumedthreadsofjavaprocesses,andprintthestackofthesethreads.
#@githubhttps://github.com/cjunn/script_tool/
#@authorcjunn
#@dateSunJan12202021:08:58GMT+0800
#
pid='';
count=5;
functionusage(){
readonlyPROG="`basename$0`"
cat<-c5#showtop5busyjavathreadsinfo
Outputcontrol:
-p,--pidfindoutthehighestcpuconsumedthreadsfrom
thespecifiedjavaprocess.
defaultfromalljavaprocess.
-c,--countsetthethreadcounttoshow,defaultis5.
Miscellaneous:
-h,--helpdisplaythishelpandexit.
EOF
}
#1.Collectscriptparameters
#2.CheckwhetherPIDexists
if[$#-gt0];
then
whiletrue;do
case"$1"in
-c|--count)
count="$2"
shift2
;;
-p|--pid)
pid="$2"
shift2
;;
-h|--help)
usage
exit0;
;;
--)
shift
break
;;
*)
shift
if[-z"$1"];then
break
fi
;;
esac
done
fi
if[!-n"$pid"];then
echo"error:-pisempty"
exit1;
fi
functionworker(){
#1.QueryallthreadsaccordingtoPID.
#2.Deleteheaderandfirstlineinformation.
#3.AccordingtothesecondcolumnofCPUtosort,reversedisplay.
#4.Deletethecount+1tolastcolumnbasedonthecountvalue.
#5.GetCPUutilization,TIDvalue,threadusedtime,andassignthemtoCPU,TID,timerespectively.
#6.PerformhexconversiononTID.
#7.UseJDKtomonitorallthreadsofjstackoutputPID.
#8.Useawktoregularlyquerythethreadinformationoftid_hexrequired.
#9.Displaythestackinformationofcountbeforethreadbusy.
localwhilec=0;
ps-mp$pid-oTHREAD,tid,time|sed'1,2d'|sort-k2-n-r|sed$[$count+1]',$d'|awk'{print$2,$8,$9}'|whilereadcputidtime
do
tid_hex=$(printf"%x"$tid);
echo"======================tid:${tid}tid_hex:${tid_hex}cpu:${cpu}time:${time}======================";
jstack$pid|awk'BEGIN{RS="\n\n+";ORS="\n\n"}/'${tid_hex}'/{print$0}'
echo"";
whilec=$[$whilec+1];
done
if[$whilec-eq0];then
echo"error:threadnotfound,makesurepidexists.";
fi
}
worker
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。