The generateThreadDumps.sh script within this article utilizes a looped execution of Java's native jstack
utility to generate a configurable quantity of thread dumps with a configurable frequency.
Script usage
Within the script file, modify the java_dir
variable to your Java installation directory. You can also optionally update the output_dir
variable if you want the thread dumps to output to a location besides your present working directory (pwd).
Next, the script can be run with the following syntax:
./generateThreadDumps.sh <pid> [ <quantity> [ <frequency> ] ]
<pid>
is the PID of the Java process for the thread dumps
<quantity>
is an optional value of the amount of thread dumps to create (default: 3)
<frequency>
is an optional value of the duration in seconds between each thread dump (default: 60)
Note that the <frequency>
does not include the time required to make the thread dump itself. This is primarily noticeable with very frequent execution, such as one second. If a thread dump takes 0.5 seconds to complete with a frequency set as 1, then the thread dumps are created once per 1.5 seconds.
Setting <frequency>
to zero will create the thread dumps in sequence.
Script download
Download generateThreadDumps.sh or copy the code below into a file:
#!/bin/sh # Modify with your Java installation directory java_dir= # Optionally modify with the output directory for thread dumps output_dir=$PWD if [ ! $java_dir ] then echo "" echo "Modify java_dir within this script with your Java installation directory" echo "" exit 1 fi if [ $# -ne 0 ] then pid=$1 # Checks if PID exists if ps -p $pid > /dev/null then # Default to 3 thread dumps, unless parameter 2 is specified quantity=${2:-3} # Default to one thread dump per 60 seconds, unless parameter 3 is specified frequency=${3:-60} echo "" echo "Collecting $quantity thread dumps $frequency seconds apart for PID $1" echo "" current_count=0 # Loop through each thread dump execution while [ $current_count -lt $quantity ] do current_time=$(date "+%Y.%m.%d-%H.%M.%S.%N") # Generate thread dump via jstack $java_dir/bin/jstack $pid > $output_dir/thread_dump_$current_time # If you need to generate thread dumps for a hung process, then comment # out the line above and uncomment the line below. This includes the -F # flag to force a thread dump # $java_dir/bin/jstack -F $pid > $output_dir/thread_dump_$current_time ((current_count++)) echo "Thread dump #$current_count collected at $current_time" # Sets a delay only if this isn't the last execution if [ $current_count -lt $quantity ] then sleep $frequency fi done echo "" echo "Thread dump collection complete" echo "" else echo "" echo "The PID $1 does not exist" echo "" exit 1 fi else echo "" echo "Specify the PID of the Java process to generate thread dumps." echo "" echo "Usage: ./generateThreadDumps.sh <pid> [ <quantity> [ <frequency> ] ] " echo "" exit 1 fi
Comments
0 comments
Please sign in to leave a comment.