Quickly Diagnose High CPU Usage in Java/Tomcat with jstack and Jstat
This article explains how to identify and resolve intermittent high CPU usage in Java/Tomcat services by analyzing thread stacks with jstack, examining GC behavior with Jstat, and using Jmap for memory inspection, providing step‑by‑step commands and practical tips for ops engineers.
Background
Most internet companies still use a PHP‑centric LNMP stack for web development, while Java dominates telecom, finance, and other enterprise domains. Operations engineers are comfortable troubleshooting PHP, but many feel lost when faced with Java environments.
Scenario
A Java‑based web service reported frequent CPU_idle alerts. Investigation showed the Java process consuming a large portion of CPU intermittently.
Specific situation (image)
Problem Analysis
The high CPU usage originates from the Java process, specifically the Tomcat server. Such spikes are often caused by full GC or other memory‑related issues, indicating problematic code paths that consume excessive CPU.
Using jstack to Locate the Issue
What is jstack?
jstack is a stack‑trace utility that prints thread stack information for a given Java process, core file, or remote debugging server.
Typical usage:
<code>jstack [option] <pid></code>Common options:
-l : long listing, includes lock information
-F : force dump when the normal command fails
-m : show both Java and native C/C++ frames
First, identify the thread IDs with the highest CPU consumption. In the example, the main process ID is 10832 and the problematic thread ID is 11358.
Details: Use ps -mp $PID -o THREAD,tid,time | sort -k 2 -r | head -20 to list threads by CPU time. Convert the decimal thread ID to hexadecimal for jstack: echo "obase=16;11358" | bc → 2C5E .
Running jstack -l 10832 revealed that a regular‑expression match in the application caused the CPU spike.
Extensions
Jstat
Jstat provides real‑time statistics about class loading, compilation, and garbage collection.
Common options:
-class : class‑loader activity
-compile : compilation activity
-gc : heap information during GC
-gcnew, -gcold, -gcpermcapacity, -gcutil : detailed GC metrics
Jmap
Jmap inspects memory allocation of a running Java program.
Typical usage:
<code>jmap [option] pid</code>Important options:
-dump:[live,]format=b,file=<filename> : dump heap in binary format
-finalizerinfo : show objects awaiting finalization
-heap : summary of heap configuration and GC algorithm
-histo[:live] : histogram of object instances
-permstat : permanent generation statistics
360 Zhihui Cloud Developer
360 Zhihui Cloud is an enterprise open service platform that aims to "aggregate data value and empower an intelligent future," leveraging 360's extensive product and technology resources to deliver platform services to customers.
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.