KB-2219 How to create a script to generate thread dumps automatically in Linux

Purpose

This article outlines how to create a script that can generate thread dumps automatically for a particular Java process. You can specify interval between each thread dump using this script.

Instructions

  1. Create a text file named ongoing_threaddumps.sh in your home directory.
  2. Copy and paste the script below in the file:
    #!/bin/bash
    parseArguments() {
    if [ $# -eq 0 ]; then
    echo >&1 "Run as appian : Usage: ongoing_threaddumps.sh <pid> <interval>"
    echo >&1 "Defaults: Interval = 30 (seconds)"
    exit 1
    fi
    pid=$1 # required
    interval=${2:-30} # defaults to 30 seconds
    }

    captureThreaddump() {
    threaddumpsDir="appian_support_threaddumps/ongoing"
    mkdir -p ${threaddumpsDir}
    jstack -l $pid > ${threaddumpsDir}/threaddump_$(date -u +"%Y_%m_%d_%H_%M_%S").log
    }

    captureTopOutputAppServer() {
    threadInfoDir="appian_support_threaddumps/ongoing_topinfo"
    mkdir -p ${threadInfoDir}
    top -Hbn1 -p $pid > ${threadInfoDir}/threadinfo_$(date -u +"%Y_%m_%d_%H_%M_%S").log
    }

    main() {
    while true
    do
    sleep $interval
    captureThreaddump
    captureTopOutputAppServer
    done
    }

    ### Begin script execution ###
    parseArguments $*
    main
  3. Run the following command to add execute permissions to the file: chmod +x ongoing_threaddumps.sh
  4. Run the script using the following syntax: ./ongoing_threaddumps.sh <java_process_pid> <interval> & disown
    • The <java_process_pid> parameter is the ID of the Java process for which you are collecting thread dumps. The <interval> parameter represents the time in seconds between each thread dump collection.
    • The script will create a series of thread dumps and top outputs inside a directory named appian_support_threaddumps located in the directory where the script exists (in this case, it will be in your home directory).
    • Below is an example command for taking indefinite thread dumps at 10-second intervals for the Java process with id 12345:
      ./ongoing_threaddumps.sh 12345 10 & disown
  5. The continuous execution of the script can be terminated using the file: kill -9 <script_pid>

Affected Versions

This article applies to all versions of Appian.

Last Reviewed: September 2022

Related
Recommended