Script to Capture JVM thread dump

#!/bin/bash

######################################################
# This script captures thread dump of a JVM in case the number of live threads exceeds a
# certain threshold. This can help in diagnosing which code possibly creates those number of threads.
######################################################

# export jvm home
varJrockitHome=/oracle/app/jrockit-jdk1.6.0_33/
# set JVM live thread threshold. Script takes TDump only when live threads exceed this number
varLiveThreadThold=5000
# set thread dump counter
varTdumpCounter=0
# set thread dump threshold. Script takes these many TDumps before exiting
varTdumpThold=3
# thread dump interval in seconds
varTdumpIntvl=15
# set WLS name. Script takes TDump this server
varWlsName=host_server1
# check the TD counter value with TD threshold value
while [ $varTdumpCounter -lt $varTdumpThold ]
do

# sleep for specified time before capturing TD or checking the process again
/bin/sleep $varTdumpIntvl

# find PID of JVM process
varPid=`ps -ef | grep java | grep $varWlsName | grep -v grep | awk '{print $2}'`
# check if the PID returned is actually a WLS java process
$varJrockitHome/bin/jrcmd -p | grep $varPid | grep "weblogic.Server"

if [ $? == 0 ]; then
# calculate number of live threads of JVM
varLiveThreads=`$varJrockitHome/bin/jrcmd $varPid -l | grep -iw java.threads.live | awk -F"=" '{print $2}'`

if [ $varLiveThreads -gt $varLiveThreadThold ]; then
/bin/date
/bin/echo "Number of threads = $varLiveThreads"
/bin/echo "Taking thread dump..."
## UNCOMMENT THE LINES BELOW TO ENABLE T-DUMPS
## /bin/echo "=== Threads Details $varTdumpCounter ===" >> thread_cpu_util_$varPid.log
## /bin/echo "Number of Live Threads = $varLiveThreads" >> thread_cpu_util_$varPid.log
## /bin/ps -Le -o pid,user,s,lwp,pcpu | grep $varPid >> thread_cpu_util_$varPid.log
## /bin/kill -3 $varPid
varTdumpCounter=`expr $varTdumpCounter + 1`
else
/bin/date
/bin/echo "Number of threads = $varLiveThreads"
fi
else
/bin/date
/bin/echo "Could not identify $varPid as a WLS JRockit JVM"
exit 1
fi
done
Advertisements