mercredi 4 mai 2016

A better jstack

Jstack is the command line tool get thread dumps out of JVM processes. Let’s improve it a bit.


jstack is a command-line utility 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.



if [[ $1 =~ ^[a-zA-Z]+$ ]]
    echo "# Trying to get thread dump of Java process with name '$1'"
    pid=`jps | grep "$1" | cut -d ' ' -f 1`
    echo $JAVA_HOME/bin/jstack $pid $@
    $JAVA_HOME/bin/jstack $pid $@
    echo "# Executing regular jstack"
    $JAVA_HOME/bin/jstack $@

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.

Do you have any hack to make tools even better? Let’s hear about that in the comments!