Backend Development 4 min read

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.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Diagnosing High CPU Usage in a Java Application with top and jstack

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.CpuHighDemo

After 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
' 1938

The output is 792 , which is the hexadecimal representation of the thread ID.

Now retrieve the stack trace:

jstack 1937 | grep -A 10 792

The 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.

BackendJavaCPU ProfilingPerformance Debuggingtop commandjstack
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.