Heap (JVM memory)
The heap is the region of JVM memory where all Java objects live. It is managed automatically by the garbage collector. The stack holds primitives, references and call frames; the heap holds objects. You can tune heap size with -Xms (initial) and -Xmx (maximum).
Heap vs stack
| Stack | Heap | |
|---|---|---|
| What lives here | Method call frames, primitive locals, object references | Object instances, their fields |
| Lifecycle | Per thread, LIFO — cleared when method returns | Globally shared, GC-managed |
| Speed | Very fast | Slower (allocation + GC) |
| Size | Small (typically a few MB per thread) | Large (up to many GB) |
Heap generations (G1GC, Parallel GC)
Most collectors divide the heap into generations: young (newly created objects), old (long-lived objects), and sometimes metaspace (class metadata). Most objects die young; garbage collecting the young generation is fast. ZGC and Shenandoah are generational as of Java 21 too, with much lower pause times.
Tuning heap size
java -Xms512m -Xmx4g -jar app.jar
# -Xms = initial heap size
# -Xmx = maximum heap size
OutOfMemoryError: Java heap space
Thrown when the heap fills up and GC can't reclaim enough memory. Diagnose with a heap dump (-XX:+HeapDumpOnOutOfMemoryError) and a tool like Eclipse MAT or VisualVM.