Skip to lesson

StackOverflowError and OutOfMemoryError: which area ran out

Every JVM memory error names the area that ran out, if you read the whole message. StackOverflowError is about one thread's stack; OutOfMemoryError is followed by a short text such as Java heap space or Metaspace that points to exactly one box of the memory map, and each box has a different first fix.

StackOverflowError: one thread's stack is full

StackOverflowError is thrown when a thread needs a new frame but its stack has no room left.

Example 1 · A getter that calls itself

FeeGetterBugDemo.javaJava
class Student {    private final String name;    private final int fee;
    Student(String name, int fee) {        this.name = name;        this.fee = fee;    }
    int getFee() {        return getFee();        // bug: calls itself forever; it should be "return fee;"    }}
public class FeeGetterBugDemo {    public static void main(String[] args) {        Student riya = new Student("Riya", 45000);        System.out.println("Fee: " + riya.getFee());    }}
Sample output
Exception in thread "main" java.lang.StackOverflowError
	at Student.getFee(FeeGetterBugDemo.java:11)
	at Student.getFee(FeeGetterBugDemo.java:11)
	at Student.getFee(FeeGetterBugDemo.java:11)
	at Student.getFee(FeeGetterBugDemo.java:11)
	...

What this code does

  • getFee() was meant to return the field, but it calls getFee() again, which calls it again, until the main thread's stack is full. Only the first lines are shown; the real trace prints the same line 1024 times and stops.
  • The repeated FeeGetterBugDemo.java:11 points straight at the bug. Writing return fee; fixes it. The program prints nothing else, because the error ends the main thread.

It almost always means recursion that never stops or goes far deeper than planned: a missing base case, a getter that calls itself, two methods that call each other, or toString() on two objects that refer to each other.

Only the thread whose stack is full gets the error; other threads keep running. The stack trace is the clue: the same line repeated again and again. HotSpot keeps at most 1024 frames of a trace by default (-XX:MaxJavaStackTraceDepth), so you see the repeating lines and the frames near main, where it all started, are cut off.

Find the bug

Which line runs the memory out?

Each snippet ends with a memory error. Tap the line that causes it, then check the fix.

Add up the numbers 1 to n. It ends with StackOverflowError.

Round 1 of 3

OutOfMemoryError: Java heap space and GC overhead limit exceeded

OutOfMemoryError: Java heap space means a new object did not fit in the heap, even after the garbage collector tried to make room.

Example 2 · An exam-results cache that keeps every PDF

ResultCacheDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class ResultCacheDemo {    public static void main(String[] args) {        int sheets = args.length > 0 ? Integer.parseInt(args[0]) : 20;        List<byte[]> cache = new ArrayList<>();     // every PDF stays reachable through this list
        for (int i = 1; i <= sheets; i++) {            cache.add(new byte[1024 * 1024]);       // one 1 MB result PDF            if (i % 5 == 0) {                System.out.println("Cached " + i + " result PDFs (" + i + " MB)");            }        }        System.out.println("Done: " + cache.size() + " MB kept on the heap");    }}
Output
Cached 5 result PDFs (5 MB)
Cached 10 result PDFs (10 MB)
Cached 15 result PDFs (15 MB)
Cached 20 result PDFs (20 MB)
Done: 20 MB kept on the heap

What this code does

  • Each result PDF is a 1 MB byte[] on the heap, and the list keeps all of them reachable. With the default heap, 20 MB is no problem.
  • On the day results come out, the same code is asked to keep thousands of PDFs. Example 4 runs it with a small heap to show what happens then.

Example 3 · A online-store app that never removes sessions

SessionLeakDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class SessionLeakDemo {    public static void main(String[] args) {        int sessions = args.length > 0 ? Integer.parseInt(args[0]) : 100_000;        Map<Integer, String> active = new HashMap<>();        for (int id = 0; id < sessions; id++) {            active.put(id, "user-" + id);          // never removed: a leak        }        System.out.println("Sessions kept: " + active.size());    }}
Output
Sessions kept: 100000

What this code does

  • Every login adds an entry to active, but nothing ever removes one. Each entry is several small heap objects: an Integer key, a String value and a map node.
  • 100,000 sessions fit easily. A real server running for days keeps adding forever, and the heap fills with many small objects instead of a few big ones.

Example 4 · Both heap errors with small heaps

Terminal
# The exam-results cache with a 16 MB heap and 100 PDFs to keepjava -Xmx16m ResultCacheDemo 100# The session leak with the Parallel collector and a 32 MB heapjava -XX:+UseParallelGC -Xmx32m SessionLeakDemo 100000000
Sample output
Cached 5 result PDFs (5 MB)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at ResultCacheDemo.main(ResultCacheDemo.java:10)

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

What this code does

  • Real runs on Java 21. With -Xmx16m, fewer than 10 PDFs fit before Java heap space: the heap also holds the JVM's own objects, and the collector needs some free room to work.
  • With the Parallel collector, the session map ended in GC overhead limit exceeded: the JVM was spending almost all its time collecting while freeing almost nothing. In two other runs it ended with Java heap space instead; which one appears depends on timing. The fix is the same: stop keeping dead sessions.

Either the program really needs more than -Xmx, or, much more often, it keeps objects reachable that it no longer needs: a cache with no limit, a map of every session ever created, a whole file read into memory.

OutOfMemoryError: GC overhead limit exceeded is the same problem caught earlier. The JVM gives up when it spends almost all its time collecting (over 98% by default) and frees almost nothing (under 2% of the heap). On HotSpot for Java 17 and 21 only the Parallel collector reports it; with the default G1 collector the same program ends with Java heap space.

OutOfMemoryError: Metaspace and unable to create native thread

OutOfMemoryError: Metaspace means class metadata reached -XX:MaxMetaspaceSize, or the machine's memory, and no classes could be unloaded, as in the previous lesson's class-loading example. A bigger heap does not help.

Example 5 · The other two OutOfMemoryError messages

Text
Exception in thread "main" java.lang.OutOfMemoryError: MetaspaceException in thread "main" java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached
In short
Metaspace → class metadata is full (classes and class loaders).
unable to create native thread → the operating system refused another thread.
Neither is fixed by a bigger -Xmx.

What this code does

  • The first line is the real message from the previous lesson's ClassFloodDemo run with -XX:MaxMetaspaceSize=16m.
  • The second is the exact text HotSpot uses on Java 17 and 21 when Thread.start() cannot get a new operating-system thread. It is not shown from a live run, because causing it on purpose can make the whole computer slow or unstable.

OutOfMemoryError: unable to create native thread comes from Thread.start() when the operating system refuses another thread: the process hit its thread limit, or there was no memory left for one more native stack. On Java 17 and 21 the message adds possibly out of memory or process/resource limits reached. The heap may be almost empty; the fix is fewer threads, not a bigger -Xmx.

Errors versus exceptions: why you rarely catch these

Both are errors, not exceptions: they extend VirtualMachineError, which extends Error, the JVM's way of saying it cannot go on normally. catch (Exception e) does not catch them; you would have to name them or catch Throwable.

Example 6 · These are Errors, not Exceptions

ErrorFamilyDemo.javaJava
public class ErrorFamilyDemo {    static String family(Class<?> type) {        StringBuilder chain = new StringBuilder(type.getSimpleName());        for (Class<?> c = type.getSuperclass(); c != null; c = c.getSuperclass()) {            chain.append(" -> ").append(c.getSimpleName());        }        return chain.toString();    }
    static void recurse() {        recurse();    }
    public static void main(String[] args) {        System.out.println(family(StackOverflowError.class));        System.out.println(family(OutOfMemoryError.class));        System.out.println("Is OutOfMemoryError an Exception? "                + Exception.class.isAssignableFrom(OutOfMemoryError.class));
        try {            recurse();        } catch (Exception e) {            System.out.println("never printed: catch (Exception) does not match an Error");        } catch (StackOverflowError e) {            System.out.println("Caught only by naming the Error: " + e.getClass().getName());        }    }}
Output
StackOverflowError -> VirtualMachineError -> Error -> Throwable -> Object
OutOfMemoryError -> VirtualMachineError -> Error -> Throwable -> Object
Is OutOfMemoryError an Exception? false
Caught only by naming the Error: java.lang.StackOverflowError

What this code does

  • Both classes extend VirtualMachineError and Error, never Exception, so catch (Exception e) skips them and only the catch (StackOverflowError e) block runs.
  • Catching it here is safe only because recurse() changes nothing. In real code, catching memory errors to carry on usually hides a broken state; this demo catches it only to show the type.

You rarely should. After a StackOverflowError, a method may have stopped halfway through an update. After an OutOfMemoryError, almost any line, even a log statement, can fail again, and other threads may already have died. The safe plan is to let the program stop, record the cause, and let a restart bring it back with the bug fixed.

Add -XX:+HeapDumpOnOutOfMemoryError to production servers: HotSpot then writes a heap dump file when the heap runs out. The Diagnosing Memory Problems module shows how to read it.

Which first step for which error

Read the full first line of the error, then start here:

  • StackOverflowError → find the repeating lines in the trace and fix the recursion (base case, loop, or your own stack); raise -Xss only for a known, bounded depth.
  • Java heap space or GC overhead limit exceeded → find what keeps objects reachable (a heap dump), fix the leak or limit the data; raise -Xmx only if the data really needs it.
  • Metaspace → count loaded classes and class loaders; find what keeps generating classes or holds old loaders.
  • unable to create native thread → count threads (a thread dump); replace thread-per-task code with a pool or, on Java 21, virtual threads.

Next step

Check your understanding

11 quick questions