Article Directory
-
-
-
- I. Introduction
- 2. Test code Test.java
- 3. Compile and run the Test.java program on Linux
- Fourth, the top command to view the cpu usage
- 5. View the thread details under the process `top -H -p 11748`
- 6. Convert the pid of `thread` 12240 to hexadecimal` printf "0x%x\n" 12240`
- Seven, jstack view `process` snapshot
- Legacy
-
-
I. Introduction
Two days ago, I wrote a subscription message queue program and passed it to Flink, added each subscribed data to the Queue queue, used while(true) to fetch data from the message queue, and the program ran normally, but later found that the CPU usage was too high, which was caused by while(true) during investigation, and now simulates the investigation process of excessive cpu.
2. Test code Test.java
public class Test {
public static void main(String[] args) {
System.out.println("测试死循环对 CPU 影响");
for (int i = 0; i < Integer.parseInt(args[0]); i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName());
while (true){
}
},"线程:"+i).start();
}
}
}
3. Compile and run the Test.java program on Linux
javac Test.java
Run the Test program and start an infinite loop thread
Fourth, the top command to view the cpu usage
By uppercase C can be sorted by CPU from large to small
It can be seen that the CPU utilization rate of Test is 100%, which is very different from that of window (window CPU 100% is stuck), my Linux server has 2 cores, and the total CPU utilization rate is 50%, and the server will not be stuck. The simple understanding is that one core runs full
5. View the thread details under the processtop -H -p 11748
As shown below, you can see that the CPU usage of 12240 进程
under 12227 线程
is up to 99.9%.
6. 线程
Convert the pid of 12240 to hexadecimal printf "0x%x\n" 12240
The purpose of this step is to retrieve threads from the process snapshot
7. 进程
Snapshot viewed by jstack
Use the jstack that comes with java jdk to view 进程
the snapshot jstack 12227|grep -A 20 0x2fd0
. You can see that the 7th line of code is caused. From the source code, you can see that it is caused by while(true). Let’s briefly talk about the grep parameter
-
grep -A n displays the n lines that match the specified content and after
-
grep -B n displays the n lines that match the specified content and before
-
grep -C n displays the matching specified content and n lines before and after it
output the entire 进程
snapshot to a filejstack 12227 >> jstack.log
Legacy
When I set the number of threads to 2, I found that the 2-core CPU is directly 100%, but the cloud server is not stuck. For
Linux, when I set the number of threads to a number greater than 2, the CPU is close to 200%, which should only affect the execution efficiency and not cause the system to freeze (guess, I have forgotten all the knowledge of the operating system, and I will record it later when I understand it). The main is the case where the number of threads is 5