Some Shell for console problem
script mointor_java_cpu.sh
This script monitors a Java process and automatically captures thread dumps when CPU usage exceeds athreshold. It provides:
- Full thread stack traces
- Top N high CPU consuming threads
- Thread statistics report (states, types, deadlock detection)
./monitor_cpu.sh <Java_PID> [CPU_Threshold] [Check_Interval] [Top_Threads] [Stack_Lines]| Parameter | Required | Default | Description |
|---|---|---|---|
| Java_PID | Yes | - | Java process ID |
| CPU_Threshold | No | 50 | CPU threshold percentage to trigger snapshot |
| Check_Interval | No | 5 | Check interval in seconds |
| Top_Threads | No | 10 | Number of top CPU threads to capture |
| Stack_Lines | No | 20 | Stack trace lines per thread |
# Monitor PID 12345, capture when CPU > 50%
./monitor_cpu.sh 12345# Trigger snapshot when CPU > 80%
./monitor_cpu.sh 12345 80# Check every 3 seconds, trigger at 60% CPU
./monitor_cpu.sh 12345 60 3# Capture top 20 threads with 30 lines of stack trace
./monitor_cpu.sh 12345 50 5 20 30# Sensitive monitoring: trigger at 30% CPU
./monitor_cpu.sh 12345 30 2 15 25When CPU exceeds threshold, 3 files are generated in ./thread_snapshots/:
Complete thread dump from jstack
Top N high CPU threads with stack traces === High CPU Threads at Thu Feb 12 15:47:00 CST 2026 === Total Process CPU: 78.5% Top 10 threads by CPU usage
┌─────────────────────────────────────────────
│ Thread ID: 4168 (0x1048) - CPU: 45.2%
└─────────────────────────────────────────────
"http-nio-2012-exec-205" #542 daemon prio=5...
Thread statistics report === Thread Statistics Report === Total Threads: 542
Thread States: RUNNABLE 12 ( 2.2%) TIMED_WAITING 480 ( 88.6%) WAITING 45 ( 8.3%) BLOCKED 5 ( 0.9%)
Thread Types (Top 10): http-nio-2012-exec 200 RabbitListener 10
Deadlock Detection: ✓ No deadlock detected
# Aggressive monitoring for troubleshooting
./monitor_cpu.sh 12345 40 2 15 30# Capture only severe cases
./monitor_cpu.sh 12345 90 10 5 15## Frequent checks with detailed stacks
./monitor_cpu.sh 12345 50 3 20 50- Run in background: nohup ./monitor_cpu.sh 12345 &
- Stop monitoring: Press Ctrl+C or kill <script_pid>
- View latest snapshot: ls -t thread_snapshots/stats_*.txt | head -1 | xargs cat
- Find Java PID: jps -l or ps aux | grep java