Operations 4 min read

How to Diagnose High CPU Usage in a Java Program (Three‑Step Guide)

This article explains a three‑step method—using top to locate the CPU‑hungry Java process, identifying the offending thread, and printing its stack with jstack—to pinpoint and resolve excessive CPU consumption in a Java application running on Linux.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
How to Diagnose High CPU Usage in a Java Program (Three‑Step Guide)

When a Java program consumes excessive CPU (even reaching 100%), you can troubleshoot it in three steps: first, use the top command to find the process with the highest CPU usage; second, locate the specific thread inside that process; third, print the thread's stack trace for analysis.

Preparation

Create a Java program that performs intensive calculations:

package com.sample.core.cpu;

public class CpuFullExample {
    private static final int times = 100000000;
    public static void main(String[] args) {
        for (int i = 0; i < times; i++) {
            Math.pow(2, i);
        }
    }
}

Compile and run it on a Linux system: java com.sample.core.cpu.CpuFullExample Step 1: Find the Process

Run top and observe the process ID (PID) that consumes the most CPU, e.g., PID 2411 with 99% usage.

Step 2: Find the Thread

Use top -Hp 2411 to list threads of the process and identify the thread ID (TID) with the highest CPU, e.g., TID 2412. top -Hp 2411 Convert the decimal thread ID to hexadecimal:

printf '%x
' 2412

The result is 96c.

Step 3: Print the Thread Stack

Use jstack to dump the stack of the process and filter for the thread using its hexadecimal ID: jstack 2411 | grep -A 10 96c The output shows the stack trace, indicating the problem occurs at line 6 of CpuFullExample, where the intensive calculation is performed.

By following these steps, you can clearly identify the exact location of the performance bottleneck in the Java code.

Credits: https://www.jianshu.com/p/a455ac8a3ef0

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaperformanceLinuxCPUtopjstack
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

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.