When a Java application goes bad it is often useful to be able to perform a thread dump to find out exactly what is happening in the JVM. This is especially useful in two situations: when one has coded up an infinite loop and when a JVM refuses to exit cleanly.

While a thread dump won't explicitly indicate where an infinite loop is it will show you which methods (and lines) are currently being executed and therefore give you a good place to start looking for problems. I've used this method a few times and find it very useful. Of course this is not a substitute for getting the code right in the first place nor for robust logging but it can get you out of a jam.

A JVM won't exit unless all thread are either stopped or daemons. When you shut down an the JVM doesn't exit simply generate a thread dump to find out what threads are still running. It is normally fairly obvious which thread or threads are stopping the JVM exiting.

Generating a Thread Dump

Windows

The Java application that you want to produce a thread dump for must be running / started in a command console. When you want to produce a thread dump press Ctrl-Break

Note: it's easier to produce a thread dump on Linux as the JVM doesn't need to be started in a console window.

Linux

If the JVM is running in a console then simply press Ctrl-\.

If the JVM is running in the background then send it the QUIT signal:

kill -QUIT process_id

There process_id is the process number of the running Java process. The thread dump will be sent to wherever standard out is redirected too.

You can generally get the process numbers of of all running Java processes with the command:

ps axf | grep java