• 线上应用故障排查之一:高CPU占用


    一个应用占用CPU很高,除了确实是计算密集型应用之外,通常原因都是出现了死循环。

    以我们最近出现的一个实际故障为例,介绍怎么定位和解决这类问题。

    根据top命令,发现PID为28555的Java进程占用CPU高达200%,出现故障。

    通过ps aux | grep PID命令,可以进一步确定是tomcat进程出现了问题。但是,怎么定位到具体线程或者代码呢?

    首先显示线程列表:

    ps -mp pid -o THREAD,tid,time

    找到了耗时最高的线程28802,占用CPU时间快两个小时了!

    其次将需要的线程ID转换为16进制格式:

    printf "%x\n" tid

    最后打印线程的堆栈信息:

    jstack pid |grep tid -A 30

    找到出现问题的代码了!

    现在来分析下具体的代码:ShortSocketIO.readBytes(ShortSocketIO.java:106)

    ShortSocketIO是应用封装的一个用短连接Socket通信的工具类。readBytes函数的代码如下:

    1. public byte[] readBytes(int length) throws IOException {
    2. if ((this.socket == null) || (!this.socket.isConnected())) {
    3. throw new IOException("++++ attempting to read from closed socket");
    4. }
    5. byte[] result = null;
    6. ByteArrayOutputStream bos = new ByteArrayOutputStream();
    7. if (this.recIndex >= length) {
    8. bos.write(this.recBuf, 0, length);
    9. byte[] newBuf = new byte[this.recBufSize];
    10. if (this.recIndex > length) {
    11. System.arraycopy(this.recBuf, length, newBuf, 0, this.recIndex - length);
    12. }
    13. this.recBuf = newBuf;
    14. this.recIndex -= length;
    15. } else {
    16. int totalread = length;
    17. if (this.recIndex > 0) {
    18. totalread -= this.recIndex;
    19. bos.write(this.recBuf, 0, this.recIndex);
    20. this.recBuf = new byte[this.recBufSize];
    21. this.recIndex = 0;
    22. }
    23. int readCount = 0;
    24. while (totalread > 0) {
    25. if ((readCount = this.in.read(this.recBuf)) > 0) {
    26. if (totalread > readCount) {
    27. bos.write(this.recBuf, 0, readCount);
    28. this.recBuf = new byte[this.recBufSize];
    29. this.recIndex = 0;
    30. } else {
    31. bos.write(this.recBuf, 0, totalread);
    32. byte[] newBuf = new byte[this.recBufSize];
    33. System.arraycopy(this.recBuf, totalread, newBuf, 0, readCount - totalread);
    34. this.recBuf = newBuf;
    35. this.recIndex = (readCount - totalread);
    36. }
    37. totalread -= readCount;
    38. }
    39. }
    40. }

    问题就出在readCount 部分。如果this.in.read()返回的数据小于等于0时,循环就一直进行下去了。而这种情况在网络拥塞的时候是可能发生的。

    至于具体怎么修改就看业务逻辑应该怎么对待这种特殊情况了。

    最后,总结下排查CPU故障的方法和技巧有哪些:

    1、top命令:Linux命令。可以查看实时的CPU使用情况。也可以查看最近一段时间的CPU使用情况。

    2、PS命令:Linux命令。强大的进程状态监控命令。可以查看进程以及进程中线程的当前CPU使用情况。属于当前状态的采样数据。

    3、jstack:Java提供的命令。可以查看某个进程的当前线程栈运行情况。根据这个命令的输出可以定位某个进程的所有线程的当前运行状态、运行代码,以及是否死锁等等。

    4、pstack:Linux命令。可以查看某个进程的当前线程栈运行情况。

    (友情提示:本博文章欢迎转载,但请注明出处:雁南飞渡

  • 相关阅读:
    【Java基础夯实】我消化后的ThreadLocal是怎样的?
    java-net-php-python-ssm创意分享网站计算机毕业设计程序
    天翼云不做备案接入,如何绑定域名,不用80端口,443端口。
    jenkins升级版本遇到的问题
    【Python】万字长文,Locust 性能测试指北
    Docker 启动容器报错:cannot allocate memory: unknown
    Are you sure you want to continue connecting (yes/no) 每次ssh进
    配置多仓库根目录(阁瑞钛伦特软件-九耶实训)
    golang工程中间件——redis常用结构及应用(string, hash, list)
    Taurus.MVC 微服务框架 入门开发教程:项目部署:5、微服务应用程序发布到Docker部署(下)。
  • 原文地址:https://blog.csdn.net/qq_34755766/article/details/128185105