Skip to lesson

Reading an OutOfMemoryError message

OutOfMemoryError is not one problem but several, and the text after the colon tells you which memory ran out. Reading that text correctly decides your first step: a heap dump, a thread dump, a class count or a look at a size calculation.

Java heap space and GC overhead limit exceeded

OutOfMemoryError is the error the JVM throws when it cannot get the memory it needs, even after garbage collection. Its message names which memory area ran out.

OutOfMemoryError: Java heap space means the JVM needed room for a new object or array, ran a GC, and still could not find enough free heap below -Xmx.

OtpCache.javaJava
import java.util.HashMap;import java.util.Map;
public class OtpCache {    // Bug: OTPs are stored but never removed    static final Map<Integer, String> OTPS = new HashMap<>();
    public static void main(String[] args) {        for (int phone = 1; phone <= 1_000_000; phone++) {            OTPS.put(phone, "OTP-" + phone);        }        System.out.println("OTPs stored: " + OTPS.size());    }}
Output
OTPs stored: 1000000

Either the program keeps too much (a leak, like the OTP map below) or it really needs more memory than it was given.

GC overhead limit exceeded means the heap is almost full and the JVM is spending nearly all its time in GC while freeing almost nothing. HotSpot's Parallel collector throws it when about 98% of the time goes to GC and less than 2% of the heap is recovered, several collections in a row, so the program fails fast instead of crawling. On JDK 21, G1 (the default) does not throw it; the same leak ends in Java heap space. For both, the first step is the same: check whether the heap after GC keeps rising (GC log, jstat), then look at a heap dump to see what is kept.

Example 1 · The same leak, three endings

Terminal
java -Xmx24m OtpCachejava -Xmx16m -XX:+UseParallelGC OtpCache
Sample output
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.HashMap.resize(HashMap.java:710)
	at java.base/java.util.HashMap.putVal(HashMap.java:669)
	at java.base/java.util.HashMap.put(HashMap.java:618)
	at OtpCache.main(OtpCache.java:10)

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
	at java.base/java.lang.Integer.valueOf(Integer.java:1073)
	at OtpCache.main(OtpCache.java:10)

What this code does

  • OtpCache (the program above) keeps 1 million OTP entries, about 100 MB with all the Integer, String and map node objects; with no flags it finishes in under a second. With a 24 MB heap and G1 (JDK 21), it ends in Java heap space while the map resizes its table.
  • With 16 MB and the Parallel collector, the JVM gave up with GC overhead limit exceeded while autoboxing a key in Integer.valueOf. Same bug, different message: both mean "the heap is full of objects that are still referenced".
  • With a 64 MB G1 heap and 2 million entries, an earlier run could not even print the trace: it showed only Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main".

Memory outside the heap: Metaspace, native threads, direct buffers

Three messages are about memory that is not the Java heap, so a bigger -Xmx does not fix them.

UploadBuffers.javaJava
import java.nio.ByteBuffer;import java.util.ArrayList;import java.util.List;
public class UploadBuffers {    // Bug: a direct buffer is kept for every upload    static final List<ByteBuffer> BUFFERS = new ArrayList<>();
    public static void main(String[] args) {        for (int upload = 1; upload <= 64; upload++) {            BUFFERS.add(ByteBuffer.allocateDirect(1024 * 1024));   // 1 MB outside the heap        }        System.out.println("Direct buffers kept: " + BUFFERS.size());    }}
Output
Direct buffers kept: 64

OutOfMemoryError: Metaspace: class metadata filled metaspace, which only happens when a limit is set with -XX:MaxMetaspaceSize (by default it can grow until native memory runs out). The usual cause is classes loaded again and again by new class loaders that are never released, as in the plugin loader below. A related message, Compressed class space, is the same problem in the part of metaspace that holds class pointers. First step: watch the loaded class count (jstat -class, or java.lang.Class in two histograms).

unable to create native thread (the thread dumps lesson) means the OS refused a new thread: take a thread dump and count the threads. Direct buffer memory errors mean ByteBuffer.allocateDirect reached its limit (-XX:MaxDirectMemorySize, by default about the maximum heap size). Java 8 and 11 print the short message Direct buffer memory; JDK 21 prints Cannot reserve N bytes of direct buffer memory (allocated: ..., limit: ...). First step: find who allocates direct buffers and why they are kept.

Example 2 · A plugin loader that leaks classes

PluginReloader.javaJava
import java.io.InputStream;import java.util.ArrayList;import java.util.List;
class FeePlugin {}
class PluginLoader extends ClassLoader {    Class<?> load(byte[] bytes) {        return defineClass("FeePlugin", bytes, 0, bytes.length);    }}
public class PluginReloader {    // Bug: every reload keeps its class, so old versions are never unloaded    static final List<Class<?>> LOADED = new ArrayList<>();
    public static void main(String[] args) throws Exception {        byte[] bytes;        try (InputStream in = PluginReloader.class.getResourceAsStream("FeePlugin.class")) {            bytes = in.readAllBytes();        }        for (int reload = 1; reload <= 20_000; reload++) {            LOADED.add(new PluginLoader().load(bytes));        }        System.out.println("Plugin versions loaded: " + LOADED.size());    }}
Output
Plugin versions loaded: 20000

What this code does

  • Every "reload" creates a new class loader and defines FeePlugin again from the same bytes. To the JVM, each one is a different class with its own metadata in metaspace. Keeping all 20000 Class objects in a list keeps all the loaders and their metadata alive.
  • With no limit, it finishes in about a second and uses some tens of MB of native memory. A plugin system or an app server that reloads code all day without releasing old loaders grows the same way, just slower.

Example 3 · Metaspace and direct buffer errors with small limits

Terminal
java -XX:MaxMetaspaceSize=16m PluginReloaderjava -XX:MaxDirectMemorySize=16m UploadBuffers
Sample output
Exception in thread "main" java.lang.OutOfMemoryError: Metaspace
	at java.base/java.lang.ClassLoader.defineClass1(Native Method)
	at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1027)
	at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:889)
	at PluginLoader.load(PluginReloader.java:10)
	at PluginReloader.main(PluginReloader.java:24)

Exception in thread "main" java.lang.OutOfMemoryError: Cannot reserve 1048576 bytes of direct buffer memory (allocated: 16777216, limit: 16777216)
	at java.base/java.nio.Bits.reserveMemory(Bits.java:178)
	at java.base/java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:111)
	at java.base/java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:360)
	at UploadBuffers.main(UploadBuffers.java:11)

What this code does

  • JDK 21. With metaspace capped at 16 MB, defineClass fails with Metaspace; the heap was nowhere near full. Raising -Xmx would change nothing here.
  • UploadBuffers (the program in this section) keeps a 1 MB direct buffer per upload. With a 16 MB limit, the 17th buffer fails, and JDK 21 says exactly how much was allocated and what the limit is.

Requested array size exceeds VM limit

OutOfMemoryError: Requested array size exceeds VM limit means the code asked for an array longer than the JVM can create at all, close to Integer.MAX_VALUE elements, whatever the heap size. HotSpot checks this before it even tries to allocate, so it fails at once.

Example 4 · An impossible array size

HugeArrayDemo.javaJava
public class HugeArrayDemo {    public static void main(String[] args) {        int rows = Integer.MAX_VALUE;              // a bad size from a broken calculation        try {            int[] marks = new int[rows];            System.out.println("Created " + marks.length);        } catch (OutOfMemoryError e) {            System.out.println("Caught: " + e.getMessage());        }        System.out.println("Max int: " + Integer.MAX_VALUE);    }}
Output
Caught: Requested array size exceeds VM limit
Max int: 2147483647

What this code does

  • An int[] of Integer.MAX_VALUE elements would need 8 GB, but HotSpot refuses the length itself, before looking at the heap. The result was the same with a 16 MB heap and a 16 GB heap, and with G1, Parallel and Serial (JDK 21).
  • Catching OutOfMemoryError is shown here only to print the message. In real code, check the size before you allocate, as the practice tab does.

This is almost always a bug in a size calculation: a length read from a corrupt file, an int overflow, or a "just make it as big as possible" constant. The fix is in the code that computes the size, never in JVM options.

An int overflow can also go the other way: 50_000 * 50_000 becomes a negative number, and new int[...] then throws NegativeArraySizeException. Multiply sizes as long and check them.

Why the stack trace shows who allocated last, not who leaked

An OutOfMemoryError is thrown in whichever thread asks for memory at the moment the heap is full. The stack trace shows that last allocation, which is often innocent: a StringBuilder growing, a HashMap resizing, an Integer.valueOf for autoboxing.

Java
// ErpBatchJob (from the Taking a heap dump lesson), the two methods that matterstatic void recordAudit(int studentNo) {    AUDIT_LOG.add(new byte[50_000]);            // kept forever: the real cause}
static String buildReportCard(int studentNo) {    StringBuilder card = new StringBuilder();    for (int subject = 1; subject <= 5000; subject++) {        card.append("Student ").append(studentNo)            .append(" subject ").append(subject).append(": PASS\n");   // line 16    }    return card.toString();                      // a big temporary String, freed every time}

The objects that really fill the heap were created earlier, maybe hours earlier, by other code. So never "fix" the method in the stack trace by reflex. Use the trace only for context, and find the real cause in a heap dump: the biggest retained objects and their path to GC roots.

Sometimes the JVM cannot even print the trace, because printing needs memory too, and you see Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main". The message is different, but the meaning is the same: the heap is full.

Example 5 · The trace blames the report card, not the audit log

Terminal
java -Xmx64m ErpBatchJob
Sample output
Processed 500 students, last card has 153893 chars
Processed 1000 students, last card has 158893 chars
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.base/java.util.Arrays.copyOf(Arrays.java:3541)
	at java.base/java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:242)
	at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:587)
	at java.base/java.lang.StringBuilder.append(StringBuilder.java:179)
	at ErpBatchJob.buildReportCard(ErpBatchJob.java:16)
	at ErpBatchJob.main(ErpBatchJob.java:24)

What this code does

  • Every run with a 48 to 128 MB heap on JDK 21 failed in buildReportCard, at line 16, while the StringBuilder grew. That method creates a big temporary string, but it is freed after each student.
  • The real cause is recordAudit, which keeps 50 KB per student in AUDIT_LOG and never appears in the trace. By the time it fails, more than 1000 students are done, so AUDIT_LOG alone holds over 50 MB of the 64 MB heap; a heap dump shows it at the top of the dominator tree.

-XX:+ExitOnOutOfMemoryError for services that should restart

After an OutOfMemoryError, a long-running service is in an unknown state. The thread that got the error may have died halfway through updating shared data, other threads keep failing, and the service may look alive while giving wrong answers.

Example 6 · Exit at the first OutOfMemoryError, after saving a dump

Terminal
java -Xmx64m -XX:+ExitOnOutOfMemoryError ErpBatchJobecho "exit $?"java -Xmx64m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dumps/erp-batch.hprof -XX:+ExitOnOutOfMemoryError ErpBatchJob
Sample output
Processed 500 students, last card has 153893 chars
Processed 1000 students, last card has 158893 chars
Terminating due to java.lang.OutOfMemoryError: Java heap space
exit 3

Processed 500 students, last card has 153893 chars
Processed 1000 students, last card has 158893 chars
java.lang.OutOfMemoryError: Java heap space
Dumping heap to dumps/erp-batch.hprof ...
Heap dump file created [65483815 bytes in 0.091 secs]
Terminating due to java.lang.OutOfMemoryError: Java heap space

What this code does

  • JDK 21. With ExitOnOutOfMemoryError, the JVM prints one line and exits with code 3 instead of throwing the error into the program. A supervisor sees a failed process and restarts it.
  • With both flags, the dump is written first and the exit comes after, so the restart does not destroy the evidence.

-XX:+ExitOnOutOfMemoryError makes the JVM exit at the first OutOfMemoryError (exit code 3 on JDK 21). That is what you want when a supervisor such as systemd, Docker or Kubernetes restarts the process: a clean restart beats a half-broken service. Combine it with -XX:+HeapDumpOnOutOfMemoryError, which writes the dump before the exit, so you keep the evidence. (-XX:+CrashOnOutOfMemoryError also exits, but writes a crash report and possibly a core file, which is heavier.) Restarting is first aid, not a cure. If the dump shows a leak, the service will run out of memory again after the same number of hours.

Next step

Check your understanding

12 quick questions