Skip to content

Instantly share code, notes, and snippets.

@eddiecorrigall
Last active June 22, 2018 14:02
Show Gist options
  • Save eddiecorrigall/877aaea4174aa5b320686128008c237a to your computer and use it in GitHub Desktop.
Save eddiecorrigall/877aaea4174aa5b320686128008c237a to your computer and use it in GitHub Desktop.
Java Threaddump
#!/bin/bash
# Usage: threaddump.sh <thread count threshold> <process name>
# Example:
# Run this command `nohup sh threaddump.sh 500 tomcat7 &` to capture a thread
# dump when httpd connections exceeds 500.
#
# Logs are written to `nohump.out` in the users home directory.
# Thread dump for tomcat will be written to `/var/log/tomcat7/catalina.out`.
THREAD_COUNT_THRESHOLD="$1"
TARGET_PROCESS_NAME="$2"
function count_httpd_threads {
ps -e | grep --count httpd
}
function get_java_pid {
PROCESS_NAME="$1"
sudo jps -l -v | awk --assign P=${PROCESS_NAME} '/P/ { print $1 }'
}
while true; do
THREAD_COUNT=`count_httpd_threads`
if [ "${THREAD_COUNT}" -ge "${THREAD_COUNT_THRESHOLD}" ]; then
PID=`get_java_pid ${TARGET_PROCESS_NAME}`
if [ -n "$PID" ]; then
echo "[$(date --iso-8601=seconds)] Thread dump [${TARGET_PROCESS_NAME}] with pid [$PID] since thread count [${THREAD_COUNT}] breaches threadshold [${THREAD_COUNT_THRESHOLD}]"
sudo kill -3 "$PID"
else
echo "ERROR: process [${TARGET_PROCESS_NAME}] not running"
fi
fi
sleep 10
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment