When troubleshooting Java performance issues, locateing threads that consume the most CPU or memory is a key step. The following are the specific inspection methods for two scenarios:
1. Find the thread that occupies the highest CPU
Step 1: Find the Java Process ID (PID)
ps -ef | grep java # Find all Java processestop -c | grep java # Real-time monitoring of Java processes (sorted by CPU)
Step 2: Find out the thread that occupies the highest CPU in the process
top -Hp <PID> # Press H to switch to thread mode, sort by CPU (default)
Key indicators:
- The %CPU column displays the CPU usage of the thread.
- Record the highest occupied thread ID (such as 12345).
Step 3: Convert thread ID to hexadecimal
printf "%x\n" <TID> # For example: printf "%x\n" 12345 → 3039
Step 4: Export thread stack using jstack
jstack <PID> | grep -A 30 'nid=0x3039' # View thread stack
Output analysis:
"http-nio-8080-exec-1" #10 daemon prio=5 os_prio=0 tid=0x00007f9c000b4800 nid=0x3039 runnable [0x00007f9bf9e2e000]
: RUNNABLE
at .socketRead0(Native Method)
at (:150)
...
Key information: thread name (such as http-nio-8080-exec-1), status (RUNNABLE), stack top method (such as socketRead0).
2. Find the thread that occupies the most memory
Method 1: Through thread stack analysis (for memory leaks)
1. Generate heap dump file (Heap Dump)
jmap -dump:format=b,file= <PID> # Generate heap snapshots
2. Use tools to analyze (such as MAT, VisualVM)
MAT(Memory Analyzer Tool):
java -jar /Contents/Eclipse/MemoryAnalyzer -data /tmp/mat_workspace
Key steps:
- Open the heap file → Leak Suspects report.
- View the "Threads" tab and view memory footprint by thread.
- Locate threads that hold a large number of objects (such as worker threads in thread pools).
Method 2: Statistics through thread allocation (JDK 11+)
Enable thread memory allocation statistics
java -XX:StartFlightRecording=settings=profile,filename= -XX:ThreadAllocationStatisticsSamplingInterval=1000 YourMainClass
Analysis using JMC (Java Mission Control)
jmc
Key steps:
- Open the JFR file → Thread → Memory allocation.
- Sort by allocation amount to find the thread that occupies the most.
3. Automated scripting tools
Script 1: Find high CPU threads with one click
#!/bin/bash # Function: Find out the thread that occupies the highest CPU in the Java process and display the stackPID=$1 if [ -z "$PID" ]; then echo "Usage: $0 <Java Process PID>" exit 1 fi # Get the thread ID that occupies the highest CPUTID=$(top -Hp $PID -b -n 1 | awk 'NR>7 {print $1; exit}') if [ -z "$TID" ]; then echo "Process $PID or no active thread found" exit 1 fi # Convert to hexadecimalHEX_TID=$(printf "%x\n" $TID) echo "CPU The highest occupied thread ID: $TID (0x$HEX_TID)" # Print thread stackecho "Stack Information:" jstack $PID | grep -A 30 "nid=0x$HEX_TID"
Script 2: Regularly monitor thread memory allocation
#!/bin/bash # Function: generate heap snapshots regularly and analyzePID=$1 INTERVAL=${2:-300} # Default 5 minutes if [ -z "$PID" ]; then echo "Usage: $0 <Java Process PID> [seconds interval]" exit 1 fi while true; do TIMESTAMP=$(date +%Y%m%d_%H%M%S) HEAP_FILE="heap_${PID}_${TIMESTAMP}.hprof" echo "[$TIMESTAMP] Generate heap snapshots: $HEAP_FILE" jmap -dump:format=b,file=$HEAP_FILE $PID # Analyze the largest thread (simplified version, actually requires MAT and other tools) echo "[$TIMESTAMP] Analysis..." # TODO: Calling the MAT API or other tools to analyze the heap file echo "[$TIMESTAMP] The next sampling will be after $INTERVAL seconds..." sleep $INTERVAL done
4. Frequently Asked Questions Scenarios and Solutions
Problem scenario | Troubleshooting method | Solution |
---|---|---|
The thread pool is full and the CPU is soaring | 1. Check whether the thread name contains pool or executor2. Check whether the stack is stuck in task execution | 1. Increase the thread pool size 2. Optimize task execution logic 3. Use bounded queues to avoid unlimited submission of tasks |
GC threads are frequently triggered | 1. View GC thread CPU usage 2. Use jstat to observe GC frequency |
1. Increase heap memory 2. Adjust the GC algorithm (such as G1, ZGC) 3. Optimize object creation mode |
Blocking threads cause memory accumulation | 1. Analyze large objects in heap dump 2. Check whether the thread holds the lock for a long time |
1. Optimize the locking particle size 2. Use lock-free data structures 3. Increase producer/consumer queue capacity |
5. Things to note
1. Performance impact:
- jstack triggers a safe point (Safepoint), which may cause the application to pause temporarily.
- Frequently generating heap dumps can take up a lot of disk space and affect performance.
2. Tool version compatibility:
There may be problems with using the same version of the tool as the target JVM (such as JDK 8's jstack to analyze the process of JDK 11).
3. Production environment suggestions:
- Priority is given to non-invasive tools (such as JFR, asynchronous sampling).
- Avoid executing multiple diagnostic commands simultaneously when high loads.
Through the above methods, problem threads can be quickly positioned and targeted optimization can be carried out to improve the stability and performance of Java applications.
This is the article about how Java locates threads that occupy the most CPU or memory in the process. For more related Java thread positioning content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!