Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Language Features by Version

Java JVM memory areas

Where Java data lives: the heap, thread stacks, metaspace, the code cache and native memory. See which errors each area throws and how to size them.

The JVM does not use memory as one big pool. It divides what it needs into several areas, each with its own purpose, lifetime and failure mode. Knowing which area is full is the first step in diagnosing OutOfMemoryError and StackOverflowError, and in choosing the right command-line option.

The areas that matter most are the heap (all objects and arrays), the thread stacks (one per thread, holding method frames), metaspace (class metadata) and native memory (everything else: the JIT code cache, direct buffers, thread structures, the JVM itself).

Java
long max = Runtime.getRuntime().maxMemory();   // upper limit of the heap, in bytes

The areas at a glance

Area Holds Shared by threads? Fails with Main option
Heap Objects, arrays, string contents Yes OutOfMemoryError: Java heap space -Xmx, -Xms
Thread stack Frames: local variables, parameters, return addresses No, one per thread StackOverflowError -Xss
Metaspace Class metadata (methods, constant pools) Yes OutOfMemoryError: Metaspace -XX:MaxMetaspaceSize
Code cache JIT-compiled machine code Yes Compilation stops, program slows -XX:ReservedCodeCacheSize
Direct memory ByteBuffer.allocateDirect, NIO, some libraries Yes OutOfMemoryError: Direct buffer memory -XX:MaxDirectMemorySize

Metaspace replaced the old "permanent generation" in Java 8. It lives in native memory, so by default it grows as needed instead of having a small fixed size.

What goes where

Local variables of primitive type, and the references to objects, live in the stack frame of the running method. The objects they point to live on the heap. When the method returns, its frame disappears at once; the objects it created stay on the heap until the garbage collector finds no references to them. Static fields live with the class metadata, but the objects they refer to are on the heap.

Try it

Java Stack versus heap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Running out of heap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Strings, interning and where equal text lives

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Command-line options (read-only)

Terminal
# Read-only: the sandbox cannot change JVM options
java -Xms512m -Xmx2g -Xss512k -XX:MaxMetaspaceSize=256m MyApp
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps MyApp
java -XX:MaxRAMPercentage=75 MyApp          # size the heap relative to container memory
java -XX:NativeMemoryTracking=summary MyApp # then: jcmd <pid> VM.native_memory summary

Usage notes

  • The heap is generational in most collectors. New objects start in a young region and move to an old region if they survive. See garbage collection.
  • -Xmx limits the heap only. The process uses more than that in total: stacks, metaspace, code cache, GC structures and direct buffers all come on top. In a container, leave headroom or use -XX:MaxRAMPercentage.
  • Modern JVMs are container-aware. Since Java 10 the default heap size is derived from the container's memory limit, not the host's.
  • Stack depth depends on frame size and -Xss. The default is typically 512 KB to 1 MB per thread on 64-bit platforms. Deep recursion in a thread you create yourself can set a bigger size through the Thread constructor.
  • Many threads multiply stack usage. Platform threads reserve their stack up front; virtual threads keep their stacks on the heap and grow as needed.
  • Memory leaks in Java are reachable-but-unneeded objects: static maps that only grow, listeners never removed, ThreadLocal values on pooled threads, unclosed resources. A heap dump (jcmd <pid> GC.heap_dump) shows who holds them.
  • System.gc() is a hint only. Production code should not call it.
  • Runtime.totalMemory(), freeMemory() and maxMemory() report heap figures that change as the heap grows or shrinks, so they are unsuitable for exact assertions.