When a Java application runs, the JVM organizes system RAM into distinct memory spaces defined by the Java Virtual Machine Specification. Mastering JVM memory management enables you to prevent OutOfMemoryError, diagnose memory leaks, and tune high-scale production systems.
| Memory Area | Thread Scope | Stored Contents | Associated Error |
|---|---|---|---|
| Heap Memory | Shared by All Threads | All class instances, objects, strings, arrays | OutOfMemoryError: Java heap space |
| JVM Stack | Per-Thread | Method call frames, local variables, primitive data | StackOverflowError |
| Metaspace (Java 8+) | Shared by All Threads | Class metadata, method bytecodes, constant pools (in native RAM) | OutOfMemoryError: Metaspace |
| Program Counter (PC) | Per-Thread | Address of current executing JVM instruction | None |
| Native Method Stack | Per-Thread | C/C++ native method call frames via JNI | StackOverflowError |
Heap memory is divided into generational spaces based on the Weak Generational Hypothesis (the observation that most objects die very shortly after creation):
new.Each active thread has its own Stack. Every time a method is invoked, the JVM pushes a new Stack Frame containing:
public class StackOverflowDemo {
public static void recursiveBomb(int count) {
// Pushes stack frames continuously without base condition
recursiveBomb(count + 1);
}
public static void main(String[] args) {
// Throws: Exception in thread "main" java.lang.StackOverflowError
recursiveBomb(1);
}
}
import java.util.ArrayList;
import java.util.List;
public class HeapOOMDemo {
public static void main(String[] args) {
List memoryLeakList = new ArrayList<>();
// Rapidly fills the Heap with 10MB byte arrays
while (true) {
memoryLeakList.add(new byte[10 * 1024 * 1024]);
}
// Throws: java.lang.OutOfMemoryError: Java heap space
}
}
| JVM Flag | Purpose & Example |
|---|---|
-Xms<size> | Initial Heap size at JVM startup (e.g., -Xms2g for 2 Gigabytes) |
-Xmx<size> | Maximum allowable Heap size (e.g., -Xmx8g) |
-Xss<size> | Stack size per thread (default ~1MB, e.g., -Xss512k) |
-XX:MaxMetaspaceSize | Upper boundary for native Metaspace (e.g., -XX:MaxMetaspaceSize=512m) |
-XX:+HeapDumpOnOutOfMemoryError | Generates a diagnostic .hprof memory dump automatically when OOM occurs |
Accelerate your Java mastery by studying these tightly connected core tutorials:
How objects are moved across Young and Old generations.
ClassLoader and Execution Engine architecture.
Understanding method call frames on the stack.
Handling OutOfMemoryError and StackOverflowError.