Which JVM tools do you reach for when diagnosing a real performance problem, and what is each one for?
There are a handful of tools that you will reach for, and each one answers a different question.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class Main {
public static void main(String[] args) {
// The basic counters.
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
System.out.println("the thread count : " + threads.getThreadCount());
System.out.println("the peak count : " + threads.getPeakThreadCount());
// The command line tools that do the real work:
// jps lists the java programs that are running
// jstack prints every thread and what it is doing
// jcmd help lists everything else that jcmd can do
// jstat -gcutil watches the garbage collector
// jmap -histo prints the biggest classes in the heap
// jcmd GC.heap_dump /tmp/dump.hprof
}
}
Here is what each one is for.
jstack prints every thread, what it is doing, and which locks it is waiting for. It is the first tool to reach for when a program has stopped responding, because the threads that are stuck tell you where the problem is.
jcmd is the one tool that does everything. It can print a thread dump, take a heap dump, ask for the garbage collector to run, and print the flags that the virtual machine was started with.
jmap shows what is in the heap. The flag -histo prints the classes with the most objects in them, which is often enough to point at the problem without taking a full dump.
jstat watches the garbage collector over time and is the quickest way to see whether the collector is the problem.
The Java flight recorder records what the program is doing for a period of time with very little overhead, and you open the file in a tool afterwards. It is the best tool for a problem that only happens sometimes, because you can leave it running and catch the problem when it happens.
The next question in this topic looks at the heap dump in more detail.