Video in progress

Strong Middle ⚙️ JVM and memory

The first request gets an ExceptionInInitializerError, and the later ones get NoClassDefFoundError. What does that mean?

The class's static initializer threw an exception on the first attempt. The JVM marks the class as being in an error state and, on every later access, throws NoClassDefFoundError without trying again.

📖 Answer

This pair confuses many people, because if you don't see the beginning of the log you think "the jar is missing". In fact the jar is right where it should be.

A typical case:

public class TaxRates {
    // RuntimeException if the file isn't found
    static final Map<String, BigDecimal> RATES = loadFromFile("/rates.csv");
}

On the first access <clinit> fails, giving an ExceptionInInitializerError (the original cause is inside, via getCause()). The JVM moves the class to an "erroneous" state. From now on every access to TaxRates immediately throws NoClassDefFoundError: Could not initialize class TaxRates. In Java 17+ the message often includes the original cause too ("Caused by: java.lang.ExceptionInInitializerError: Exception ... [in thread ...]"), but not always.

What to do:

  1. Look in the log for the first error, close to the time the application started.
  2. Don't touch the network, files or the database in a static initializer. Move that kind of thing into a bean or into lazy code that can be retried.
  3. The class won't recover until you restart the application. Tell the ops team that too.

Don't confuse it with ClassNotFoundException: that one appears when a class isn't found at all, usually on dynamic loading through Class.forName or a loader.