A better jstack

Jstack is the command line tool get thread dumps out of JVM processes. Let’s improve it a bit so that we can call jstack <classFQN>.

Presentation

jstack is a CLI tool that connects to a JVM identified by its PID and creates a thread dump. It is very handy. However I don’t like to type PIDs. Wouldn’t it be much better if it could identify a JVM based on part of the main class name?

Jstack by name

My initial solution was to type something along the lines of jstack $(jps | grep MyClass | cut -d ' ' -f 1). That’s good but not great. Instead, I came up with that simple script that I added before $JAVA_HOME/bin in my PATH.

1 2 3 4 5 6 7 8 9 10 11 12 13
#!/bin/bash if [[ $1 =~ ^[a-zA-Z]+$ ]] then echo "# Trying to get thread dump of Java process with name '$1'" pid=`jps | grep "$1" | cut -d ' ' -f 1` shift echo $JAVA_HOME/bin/jstack $pid $@ $JAVA_HOME/bin/jstack $pid $@ else echo "# Executing regular jstack" $JAVA_HOME/bin/jstack $@ fi

That’s it. Now I can use jstack MyClass. It is a simple hack but I have found it very useful over the last months. Even better, it does not prevent using regular jstack command-line parameters.

A word about thread dumps

Reading thread dumps can be cumbersome. To filter them or query them, mjprof can be useful. It is a thread-dump parser written by Haim Yadid (lifey on Github). I find it a bit difficult to use, but once you get your first filters working, it is quite useful.