Sub topic 1
Where the JVM keeps your data
A running Java program stores data in several different places, and each place has its own size limit, its own failure message and its own tuning flag. When you see OutOfMemoryError or StackOverflowError, the first question is which area ran out. This chapter maps those areas. Later chapters cover the heap, the collectors and diagnosis in detail.
Prerequisites
This chapter assumes you can:
- Read and write basic Java, including classes, methods, fields and local variables.
- Tell an object from a reference to it. A variable of class type holds a reference, not the object itself.
- Compile and run a program with
javacandjavafrom a terminal.
You do not need to know how garbage collection works yet. It is introduced from the next chapter onward.
The JVM runtime data areas
The Java Virtual Machine (JVM) specification defines a set of runtime data areas. HotSpot, the JVM in OpenJDK and Oracle JDK, implements them as follows.
| Area | Shared or per thread | What it holds | Main sizing flag |
|---|---|---|---|
| Heap | Shared by all threads | Objects and arrays, including strings | `-Xms`, `-Xmx` |
| Java thread stack | One per thread | Stack frames: local variables, operand stack, return info | `-Xss` |
| Program counter (PC) register | One per thread | Address of the bytecode instruction being executed | Not configurable |
| Native method stack | One per thread | Frames for native (C/C++) code called through JNI | Platform dependent |
| Metaspace | Shared | Class metadata: field and method descriptions, runtime constant pools | `-XX:MaxMetaspaceSize` |
| Code cache | Shared | Machine code produced by the JIT compiler | `-XX:ReservedCodeCacheSize` |
| Direct memory | Shared | Buffers from `ByteBuffer.allocateDirect` and similar | `-XX:MaxDirectMemorySize` |
The heap and the stacks are the areas you will deal with most often. The other areas matter when a process uses more memory than -Xmx suggests.
Shared and per-thread memory
The first split to learn is between memory that all threads see and memory that belongs to one thread.
Shared areas, such as the heap, are visible to every thread. This is why two threads can hold references to the same object, and why shared mutable objects need synchronization. The garbage collector manages the heap, so objects there are reclaimed automatically once nothing can reach them.
Per-thread areas are created when a thread starts and released when it ends. No other thread can read your local variables, so they need no synchronization. No garbage collector is involved either. A frame is removed when its method returns.
The Java thread stack
Each call to a method pushes a frame onto the calling thread's stack. The frame holds:
- The method's local variables and parameters.
- An operand stack used while evaluating expressions.
- A reference to the runtime constant pool of the method's class.
- Information needed to return to the caller.
Primitive locals (int, double, boolean and so on) live directly in the frame. For an object, the frame holds only the reference. The object itself lives on the heap.
public class FrameDemo {
static int square(int n) {
int result = n * n; // n and result live in square's frame
return result;
}
public static void main(String[] args) {
int x = 7; // primitive: stored in main's frame
StringBuilder sb = new StringBuilder("hi"); // reference in frame, object on heap
System.out.println(square(x) + " " + sb);
}
}When main calls square, a second frame is pushed. When square returns, that frame is popped and its variables are gone. The StringBuilder object stays on the heap until nothing refers to it.
Stack size and StackOverflowError
Every thread's stack has a fixed maximum size, set with -Xss. The default on 64-bit Linux is typically 1 MB, but it varies by platform. If method calls nest deeper than the stack allows, the JVM throws StackOverflowError. The usual cause is unbounded recursion:
public class Recurse {
static int depth = 0;
static void down() {
depth++;
down(); // no base case
}
public static void main(String[] args) {
try {
down();
} catch (StackOverflowError e) {
System.out.println("Overflow at depth " + depth);
}
}
}The depth you reach depends on -Xss and on how large each frame is. Run it with java -Xss256k Recurse and with java -Xss4m Recurse and compare. Raising -Xss is rarely the right fix for a real overflow, since it usually hides a missing base case. Because every thread reserves its own stack, a large -Xss multiplied by thousands of threads also uses a lot of memory.
The heap
The heap is where objects and arrays live. Every new expression allocates there, with the main exception of objects the JIT compiler can prove never escape a method. For those it may avoid heap allocation altogether (escape analysis), but you cannot count on that when reasoning about your program.
The heap is the only area the garbage collector reclaims in the normal sense, and it is the area -Xmx limits. Three numbers describe it:
- Maximum (
-Xmx): the most the heap can ever grow to. - Initial (
-Xms): the size requested at startup. - Committed: the size the JVM has actually claimed from the operating system right now. It sits between initial and maximum and can grow and shrink while the program runs.
If you do not set -Xmx, HotSpot picks a default. The usual default maximum is one quarter of the machine's physical memory. In a container, JDK 10 and later (including 11) read the container's memory limit instead of the host's. On older JDK 8 builds that was not the case, which caused many surprise out-of-memory kills.
The program below prints these numbers.
public class MemoryInfo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
long mb = 1024 * 1024;
System.out.println("Max heap: " + rt.maxMemory() / mb + " MB");
System.out.println("Total heap: " + rt.totalMemory() / mb + " MB");
System.out.println("Free heap: " + rt.freeMemory() / mb + " MB");
}
}Compile it and run it with explicit sizes:
javac MemoryInfo.java
java -Xms64m -Xmx256m MemoryInfoExpect "Max heap" to be close to 256 MB and "Total heap" to be close to 64 MB. The exact figures differ by collector, because some collectors reserve part of the heap for internal use. Names can mislead here. totalMemory() is the committed heap, not the maximum. freeMemory() is the unused part of the committed heap. The memory still available to the program is therefore maxMemory() - totalMemory() + freeMemory().
Metaspace
When the JVM loads a class, it stores that class's metadata in Metaspace. This includes the method bytecode, field descriptions and the runtime constant pool. Metaspace replaced the older permanent generation (PermGen) in JDK 8. Unlike PermGen, Metaspace uses native memory from the operating system and by default has no fixed upper limit. It grows until the system refuses. Set -XX:MaxMetaspaceSize to cap it, and expect OutOfMemoryError: Metaspace if the cap is reached.
Class metadata is not the same as class data. The Class object that you get from Foo.class is an ordinary heap object. Interned strings and static fields also live on the heap, not in Metaspace. This has been true since JDK 7 for strings and since JDK 8 for statics. Metaspace growth is usually tied to many loaded classes. Typical causes are heavy use of dynamic proxies, bytecode generation, or an application server that reloads applications without releasing old class loaders.
Memory outside the heap
-Xmx limits only the heap. The operating system sees the whole process, which also includes:
- Metaspace.
- The code cache holding JIT-compiled code.
- Every thread's stack.
- Direct buffers, which are native memory allocated by
ByteBuffer.allocateDirectand used heavily by networking libraries such as Netty. - The JVM's own internal structures, including the garbage collector's bookkeeping.
A process started with -Xmx512m can therefore use well over 512 MB of resident memory. This gap is the usual reason a container with a 512 MB limit gets killed by the operating system even though the heap never filled. As a rule, leave headroom between -Xmx and the container limit.
To see where native memory goes, start the JVM with Native Memory Tracking and ask for a summary:
java -XX:NativeMemoryTracking=summary -Xmx256m MemoryInfo
jcmd <pid> VM.native_memory summaryHere <pid> is the process ID of the running JVM. The report lists heap, class, thread, code and other categories with reserved and committed sizes. Tracking adds a small overhead, so enable it deliberately rather than leaving it on everywhere.
Which area ran out?
Each area fails with its own symptom, which tells you where to look.
| Symptom | Area | First thing to check |
|---|---|---|
| `StackOverflowError` | Java thread stack | Recursion without a base case, or a too-small `-Xss` |
| `OutOfMemoryError: Java heap space` | Heap | Live data size versus `-Xmx`, and possible leaks |
| `OutOfMemoryError: Metaspace` | Metaspace | Class loader leaks, dynamic class generation |
| `OutOfMemoryError: Direct buffer memory` | Direct memory | Unreleased direct buffers, `-XX:MaxDirectMemorySize` |
| `OutOfMemoryError: unable to create native thread` | Thread stacks and OS limits | Thread count, `-Xss`, OS process limits |
| Process killed with no Java exception | Whole process | Resident size versus container limit |
Summary of the model
Memory is organised by lifetime and sharing:
- Data tied to a method call lives in a stack frame and disappears when the method returns.
- Objects live on the shared heap and live as long as something can reach them.
- Class definitions live in Metaspace and live as long as their class loader does.
- Compiled code, direct buffers and JVM internals live in native memory outside
-Xmx.
Exercise
A service runs in a container limited to 1 GB with -Xmx1g. It is repeatedly killed by the operating system, yet heap usage reported inside the JVM never reaches the maximum and no OutOfMemoryError appears in the logs. Explain why this can happen, and name one change and one tool you would use to investigate.
Show answer
-Xmx limits only the heap. The process also needs memory for Metaspace, the code cache, thread stacks, direct buffers and JVM internals. With the heap alone allowed to reach 1 GB, total resident memory can exceed the container limit, so the operating system kills the process before the JVM throws any exception. Lower -Xmx to leave headroom (for example 600 to 700 MB), and run the JVM with -XX:NativeMemoryTracking=summary, then use jcmd <pid> VM.native_memory summary to see which non-heap categories are using the memory.
Exercise
In the method void run() { int count = 3; List<String> names = new ArrayList<>(); }, which parts are stored in the thread's stack frame and which on the heap?
Show answer
The primitive count and the reference variable names are stored in the frame of run. The ArrayList object itself, and the array it uses internally, are on the heap. When run returns, the frame and the reference are discarded, and the ArrayList becomes eligible for collection if nothing else refers to it.