Monday, April 18, 2011

Redirect thread dump to another file?

On Jboss or Tomcat application server, we usually use kill -3 PID to get thread dump to default STDOUT which is catalina.out under $Tomcat_Home/logs folder. It might be nature to use command kill -3 PID > some.file 2>&1 to try to redirect the thread dump info to some.file than default one. However, it will not work. The reason is kill is just a command to send a signal to a process. You are redirecting the output of the kill command itself rather than the process (what the process does upon receipt of a signal is separate), so the redirect (supposed to kill command itself) has no effect on which file the process (PID) will write to. Given that, if we need redirect thread dump for that process to some other file, we need add redirects to that process when it starts.

Another popular way is to use jstack -F PID to get the whole thread dump forcefully."jstack": A JVM troubleshooting tool that prints stack traces of all running threads of a given JVM process, a Java core file, or remote debug server. It comes with JDK so it is free too. :-) 


If installed/available, we recommend using the jstack tool. It prints thread dumps to the command line console.
To obtain a thread dump using jstack, run the following command:
You can output consecutive thread dumps to a file by using the console output redirect/append directive:
jstack >> threaddumps.log

jstack script

Here's a script, taken from that will take a series of thread dumps using jstack.

if [ $# -eq 0 ]; then
    echo >&2 "Usage: jstackSeries [ [ ] ]"
    echo >&2 "    Defaults: count = 10, delay = 0.5 (seconds)"
    exit 1
pid=$1          # required
user=$2         # required
count=${3:-10}  # defaults to 10 times
delay=${4:-0.5} # defaults to 0.5 seconds
while [ $count -gt 0 ]
    sudo -u $user jstack -l $pid >jstack.$pid.$(date +%H%M%S.%N)
    sleep $delay
    let count--
    echo -n "."

Just run it like this:
sh [pid] [cq5serveruser] [count] [delay]
For example:
sh 1234 cq5serveruser 10 3

Kuldeep Sharma