Video in progress

Strong Middle ⚙️ JVM and memory

In the prod log, a NullPointerException shows up as a single line with no stack trace. What is the reason?

C2 replaces "internal" exceptions that are thrown often at the same spot (NPE, ArithmeticException, ArrayIndexOutOfBounds, ClassCast) with a preallocated object that has no stack trace. This is the OmitStackTraceInFastThrow optimization, and it is on by default.

📖 Answer

The picture is usually like this: when the service started, the log had NPEs with full stack traces, but a few hours later there is only:

java.lang.NullPointerException

No line number, no method. The helpful NPE message (Java 14+, "Cannot invoke ... because ... is null") is gone too.

The reason: when these JVM-thrown exceptions occur very often in hot code, creating them each time (and fillInStackTrace) is expensive. When C2 recompiles such a method, it puts a ready-made "silent" exception at the throw site. The application keeps working correctly (the exception is still thrown and caught), but the diagnostics are lost.

What to do:

  1. Look in the log for the very first NPE: the ones logged before compilation have full stack traces.
  2. Turn the optimization off while you diagnose:
-XX:-OmitStackTraceInFastThrow

Many teams leave this on permanently. The cost is that CPU and allocation go up in a case where thousands of exceptions per second really are thrown. But such a case is itself a bug, and it needs fixing.

And the main lesson: if this optimization kicked in, it means one place in the code is throwing an NPE thousands of times and someone is catching and swallowing it. Getting the stack trace back is the first step to finding the problem itself.