Diagnosing High CPU Usage in a Java Application with top and jstack
This guide explains how to locate the cause of sudden CPU spikes in a Java program by using the top command to identify the offending process and thread, converting the thread ID to hexadecimal, and analyzing stack traces with jstack to pinpoint the problematic code line.
When a Java application suddenly consumes excessive CPU, you can follow these steps to pinpoint the issue.
1. Use top to find the process ID (PID) with the highest CPU usage and note it.
2. Run top -Hp <PID> to list the threads of that process and record the thread ID (TID) that shows the highest CPU consumption.
3. Convert the decimal thread ID to hexadecimal, which is required for the next command.
4. Print the stack trace of the identified thread using jstack <PID> | grep -A 10 <hex‑TID> and examine the output.
Below is a sample Java program that deliberately consumes a lot of CPU:
package com.sample.interview.core.jvm;
public class CpuHighDemo {
// Define a large loop count to keep the CPU busy
private static final int counter = 100000000;
public static void main(String[] args) {
for (int i = 0; i < counter; i++) {
Math.sqrt(Math.pow(10, i));
}
}
}Run the program on a Linux server:
java com.sample.interview.core.jvm.CpuHighDemoAfter the program starts, top shows a process (e.g., PID 1937) with high CPU usage. Listing its threads reveals the thread ID 1938 as the most CPU‑intensive.
Convert the thread ID to hexadecimal:
printf '%x
' 1938The output is 792 , which is the hexadecimal representation of the thread ID.
Now retrieve the stack trace:
jstack 1937 | grep -A 10 792The result points to the line in CpuHighDemo.java (line 7) where the heavy computation occurs, allowing you to quickly locate the performance bottleneck.
By following these steps, you can efficiently diagnose and resolve high CPU usage problems in Java applications.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.