1. Background:
First execute a java program which opens two threads and prints in the while loop respectively.
# java -cp ./test-threads.jar com.spiro.Main
2. Phenomenon:
View the current CPU situation with the top command
You can see that a java process occupies too much CPU. Let's check what thread and what code causes the CPU to be too high.
3. Steps
First obtain the PID of 2023, as you can see in the above figure, or obtain it through the jps command. Execute the following commands:
# top -H -p2023
Description: -H refers to the display thread, -p refers to the specified process
result:
You can see two threads with high CPU usage, write down PID 2033 and 2034 (the PID here is the thread ID identifier), convert it from decimal to hexadecimal, and use the calculator that comes with windows come and go. The results are 7f1 and 7f2 respectively
Then use the jstack command to obtain the current thread stack, which can be temporarily saved to a file tempfile.txt;
# jstack -l 2023 > tempfile.txt
Find threads with nid=0x7f1 in tempfile.txt:
You can see the thread Thread-0 we found, as well as the state of the thread and the line of code being executed, in this case the 15 lines of the Worker class are currently being executed. Then you can go to the code to see the unreasonable logic
4. Summary
This method is very useful. I have used this method many times to locate performance problems in the program, and share and record it here.