Make writing a habit together! This is the 13th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.

Jstack tool

The jstack (Stack Trace for Java) command is used to generate a snapshot of the current thread (commonly known as a threaddump file).

A thread snapshot is a stack of methods that are being executed by each thread of a VM. A thread snapshot is usually generated to locate the cause of a thread’s long pause, such as deadlocks, loops, and long suspension caused by requests for external resources.

When a thread pauses, it looks at the call stack of each line layer through JStack to see what the unresponsive thread is doing in the background or waiting for resources.

Jstack command format:

jstack [option] vmid
Copy the code

JDK 1.8, operating system Ubantu 20.04.

Check whether the CPU usage is high

Let’s start by writing a simple loop to simulate high CPU usage.

The test code is as follows:

public class MathTest {

    public int compute(a) {
        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(); }}}Copy the code

Compile and execute the following commands:

// Execute javac mathtest.java // execute Java Mathtest&in the backgroundCopy the code

The core step

  1. jpsPrint the Java process (to see if it is started)
zhengsh@zhengsh:/opt/apps$ jps
4541 MathTest
4559 Jps
Copy the code
  1. topCommand to query the thread information of a specified process, and then sort by shift + m
top -Hp 4541
Copy the code

The results are as follows:

Find the thread ID with high CPU usage4542

  1. Convert to hexadecimal by PID
printf "%x\n" 4542
11be
Copy the code
  1. The next 30 lines of the query
Jstack 4541 | grep 11 be - A 30 / / display the results are as follows:  "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: 5Copy the code

We can query the MathTest class 13 lines are running, and look back at the code:

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

The resources

  • In-depth Understanding of THE FOURTH edition of JVM Virtual Machines by Zhiming Zhou