What is the difference between OutOfMemoryError types (heap space vs metaspace vs stack overflow)?

8 minadvancedoutofmemoryerrorstackoverflowerrordiagnostics

Quick Answer

'OutOfMemoryError: Java heap space' means the heap is full of reachable objects and the GC can't free enough — usually a genuine leak or an undersized heap for the workload. 'OutOfMemoryError: Metaspace' means class metadata (loaded classes) has exceeded its limit, often from dynamic class generation/class-loader leaks. StackOverflowError (a separate Error, not OutOfMemoryError) means a single thread's call stack exceeded its size limit, almost always from excessive or infinite recursion.

Detailed Answer

These errors point at very different underlying problems, and the exact message matters for diagnosis:

  • OutOfMemoryError: Java heap space: the heap is full of objects the GC considers reachable (so it can't reclaim them), and there's no room for a new allocation even after a full GC. Usually means either a genuine memory leak (see the leak-causes question) or a heap that's simply undersized for legitimate peak memory usage — check with -Xmx, and confirm via a heap dump whether object counts for specific types are abnormally high (leak) or the whole application's working set is just larger than the configured max heap.

  • OutOfMemoryError: Metaspace: class metadata (loaded Class objects, method bytecode, etc., stored in Metaspace — off-heap since Java 8, replacing the old PermGen) has exceeded its limit (-XX:MaxMetaspaceSize, unlimited by default up to available native memory). Common causes: dynamic proxy/bytecode generation frameworks (some ORMs, mocking libraries) creating classes repeatedly without ever unloading them, or a class loader leak — e.g., repeatedly redeploying a web app without its previous class loader (and every class it loaded) ever becoming garbage.

  • StackOverflowError: technically an Error, not an OutOfMemoryError at all — a single thread's call stack exceeded its configured maximum size (-Xss), almost always due to excessive or infinite recursion (a base case that's never reached, or genuinely very deep legitimate recursion). Increasing -Xss can be a valid fix for genuinely deep-but-finite recursion, but is more often a band-aid over a recursion bug.

Diagnosis approach: heap space errors call for a heap dump analysis (object retention); metaspace errors call for checking class-loading patterns/class loader leaks; stack overflow calls for reviewing the recursive call path in the stack trace for a missing or unreachable base case.