High CPU usage of JVM tuning

Get into the habit of writing together! This is the 13th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the event details .

jstack tool

The jstack (Stack Trace for Java) command is used to generate a thread snapshot (generally called a threaddump file) at the current moment.

A thread snapshot is a collection of method stacks that each thread of the current virtual machine is executing. The purpose of generating a thread snapshot is usually to locate the cause of the thread's long pause, such as inter-thread deadlock, infinite loop, and long-term suspension caused by requesting external resources. etc., are the reasons for the long pause of the thread.

When the thread is paused, you can check the call stack of each line layer through jstack, and you can know what the unresponsive thread is doing in the background, or what resources it is waiting for.

jstack command format:

jstack [option] vmid
复制代码

Let's start practicing and talk about the environment: jdk 1.8, Operating system ubantu 20.04.

Troubleshoot high CPU usage

Let's first write a simple infinite loop program to simulate the problem of high CPU usage.

The test code is as follows:

public class MathTest {

    public int compute() {
        int a = 1026;
        int b = 2018;
        return (a + b) * 10;
    }

    public static void main(String[] args) {
        MathTest math = new MathTest();
        //System.out.println(math.compute());
        while (true) {
            math.compute();
        }
    }
}
复制代码

The compile and execute commands are as follows:

// 编译
javac MathTest.java

// 后台执行
java MathTest &
复制代码

core steps

  1. jpsPrint the Java process (see if it starts)
zhengsh@zhengsh:/opt/apps$ jps
4541 MathTest
4559 Jps
复制代码
  1. topcommand, query the thread information of the specified process, and then sort by shift + m
top -Hp 4541
复制代码

The result is as follows:

Find the thread id with high CPU usage4542

  1. Convert to hexadecimal by pid
printf "%x\n" 4542
11be
复制代码
  1. 30 lines after the query
jstack 4541|grep 11be -A 30

// 显示结果如下:
"main" #1 prio=5 os_prio=0 tid=0x00007f8efc00a800 nid=0x11be runnable [0x00007f8f016a3000]
   java.lang.Thread.State: RUNNABLE
	at MathTest.main(MathTest.java:13)

"VM Thread" os_prio=0 tid=0x00007f8efc074000 nid=0x11c1 runnable 

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f8efc01f800 nid=0x11bf runnable 

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f8efc021000 nid=0x11c0 runnable 

"VM Periodic Task Thread" os_prio=0 tid=0x00007f8efc0d9000 nid=0x11c8 waiting on condition 

JNI global references: 5
复制代码

We can query that the MathTest class line 13 is running, looking back at the code:

Here is an infinite loop call, causing the CPU to be too high. Problem found and solved.

References

  • "In-depth understanding of JVM virtual machine fourth edition" Zhou Zhiming

Guess you like

Origin juejin.im/post/7086081411915989022