Video in progress

You need to look at the machine code the JIT generated. How do you work with hsdis, PrintAssembly and JITWatch, and when is it worth it?

-XX:+PrintAssembly with the hsdis disassembler library prints the JIT code as assembly, and JITWatch reads the LogCompilation XML and shows the inlining and escape analysis decisions next to the source code. This is the last step, worth it only when a profile and JMH have led you to exactly one hot method.

📖 Answer

Often the question is "why is this method slower than expected?", and the answer is not in the assembly but in the JIT's decisions: a call that wasn't inlined, an allocation that wasn't removed, a loop that wasn't vectorized. That is why I start with JITWatch.

java -XX:+UnlockDiagnosticVMOptions -XX:+LogCompilation -XX:LogFile=jit.xml \
     -XX:+PrintInlining -jar app.jar

In JITWatch (load jit.xml and the source code):

  • which tier the method is at and how many times it has been recompiled;
  • every call site: was it inlined, and if not, why (too big, hot method too big, megamorphic);
  • escape analysis: which allocations were removed;
  • "TriView": source, bytecode and assembly side by side.

If you need the assembly, you need hsdis. It doesn't come with the JDK (for licensing reasons): you build hsdis-amd64.so for your OS and architecture, or get it from a trusted source, and put it in $JAVA_HOME/lib/server/.

-XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly \
-XX:CompileCommand=print,com.acme.Codec::decode

PrintAssembly for a whole application produces gigabytes of output, so pick a single method with CompileCommand=print. In JMH, -prof perfasm together with Linux perf shows the hottest instructions, which is more convenient.

When it isn't worth it: for a method that takes 2% of CPU, or when the problem is in I/O or the DB. This kind of analysis takes several hours, and the result may differ when the JDK version changes. But for a library core or very hot computation code, it is the only exact answer to "why".