Sub topic 4
Where data lives: heap, metaspace and thread stacks
This chapter assumes you can write and run basic Java programs, that you know what static members, references and exceptions are, and that you can pass flags to the java command. It covers the memory areas the JVM sets up while a program runs. It doesn't cover garbage collection algorithms or the layout of stack frames. Later chapters cover frames in detail.
The big picture
When you start java, the operating system creates one process. The JVM reserves memory inside that process and divides it into runtime data areas. Each area has a different job, a different lifetime and a different way of failing.
The table summarizes the three areas you will deal with most.
| Area | Shared? | Holds | Sized by | Typical failure |
|---|---|---|---|---|
| Heap | All threads | Objects, arrays, `Class` objects, interned strings | `-Xms`, `-Xmx` | `OutOfMemoryError: Java heap space` |
| Metaspace | All threads | Class metadata, run-time constant pools, method bytecode | `-XX:MaxMetaspaceSize` | `OutOfMemoryError: Metaspace` |
| Thread stack | One per thread | Frames: local variables and the operand stack | `-Xss` | `StackOverflowError` |
The heap
The heap is where every object and array lives. When you write new Where() or new int[4], the JVM allocates the memory on the heap and gives you a reference to it. The heap is shared by all threads, which is why two threads can see the same object, and why you need synchronization when they change it.
The garbage collector manages the heap. You never free an object yourself. The collector reclaims an object once no thread can reach it through references. The heap starts at the size given by -Xms and can grow up to the limit given by -Xmx. If you leave -Xmx unset, the JVM picks a default based on the machine's physical memory, commonly a quarter of it.
The heap also holds some things you may not expect:
- The
java.lang.Classobject for each loaded class. This object is called the class mirror. In HotSpot, the values of static fields are stored in it. - Interned strings, which include string literals. This has been true since Java 7.
- Arrays of every kind, including arrays of primitives such as
int[].
Metaspace
Metaspace holds the JVM's internal description of each loaded class. This includes the parsed form of the class file: field and method descriptions, the bytecode of each method, and the run-time constant pool built from the class file's constant pool.
Metaspace is not part of the heap. It lives in native memory, which means memory the operating system gives to the process outside the Java heap. It replaced the older permanent generation (PermGen) in Java 8. By default, metaspace has no fixed upper limit and grows until the machine runs out of memory. That is why production systems often set -XX:MaxMetaspaceSize.
Metaspace memory is released when the class loader that defined a class becomes unreachable and is garbage collected. All classes defined by that loader are unloaded together. Classes loaded by the bootstrap, platform and application loaders stay for the life of the program in practice. Custom loaders are different. A program that keeps creating loaders and holding references to them, as some application servers and plugin systems do, leaks metaspace. Later chapters on class loaders and class identity cover this.
A small region called the compressed class space also lives in native memory. It stores class pointers in a compact form on 64-bit JVMs. It has its own limit, -XX:CompressedClassSpaceSize.
Thread stacks
Each thread has its own stack, created when the thread starts and discarded when it ends. Every method call pushes a frame holding that call's local variables and its working area for bytecode, the operand stack. Returning from the method pops the frame. A later chapter looks inside frames. Here the important point is what a stack holds:
- Primitive local variables (
int,doubleand so on) are stored directly in the frame. - Reference local variables store the reference in the frame. The object it points to is on the heap.
Because stacks are private to a thread, local variables need no synchronization. Nothing else can see them.
Each thread also has a program counter register, which records the bytecode instruction the thread is executing. Threads that call native code (through JNI) also have a native method stack. Both are small and rarely matter in practice.
Thread stacks are allocated from native memory, not from the Java heap. The default size is 1 MB per thread on 64-bit Linux, and you change it with -Xss. Ten thousand threads at 1 MB each reserve about 10 GB of address space. When the process cannot create another thread, you see OutOfMemoryError: unable to create native thread. That error is not a heap problem, and raising -Xmx won't fix it.
Tracing one program
This program touches all three areas.
public class Where {
static int counter = 0;
private final int[] data = new int[4];
int sum(int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += i;
}
return total;
}
public static void main(String[] args) {
Where w = new Where();
int result = w.sum(5);
counter = result;
System.out.println(counter);
}
}| Item | Where it lives |
|---|---|
| `Where`'s method bytecode and constant pool | Metaspace |
| `counter` | The `Where.class` mirror object on the heap |
| The `Where` instance `w` | Heap |
| The `int[4]` array in `data` | Heap |
| Reference `w` in `main` | `main`'s frame on the main thread's stack |
| `result`, `total`, `i`, `n` | Frames on the main thread's stack |
The Where object and its array are on the heap, and w points to them. When main returns, its frame disappears. The object then has no references to it, so the garbage collector may reclaim it.
Escape analysis is a JIT optimization that can change the physical picture. If the compiler proves an object never escapes the method that creates it, it can skip the heap allocation and keep the object's fields in registers or on the stack. This does not change the behavior your program can observe. The model above is the one to reason with, but you should not be surprised if a profiler shows fewer allocations than your code appears to make.
Looking at the areas from inside Java
The java.lang.management package reports the JVM's memory pools. This lets you see the heap and non-heap areas without any external tool.
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
public class Pools {
public static void main(String[] args) {
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
String kind = pool.getType() == MemoryType.HEAP ? "heap" : "non-heap";
long used = pool.getUsage().getUsed();
System.out.printf("%-35s %-9s used=%d bytes%n", pool.getName(), kind, used);
}
}
}On a default Java 11 JVM using the G1 collector, the output includes pools named G1 Eden Space, G1 Survivor Space and G1 Old Gen (heap), plus Metaspace and Compressed Class Space (non-heap). Pool names change with the garbage collector, and the code cache appears as several CodeHeap pools. The code cache holds the machine code the JIT compiler produces, a topic for the last chapter of this tutorial.
Failures you can provoke
Each area fails in its own way. Running these small programs makes the error messages familiar before you meet them in production.
Stack overflow
public class Depth {
static int depth = 0;
static void recurse() {
depth++;
recurse();
}
public static void main(String[] args) {
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("Overflow at depth " + depth);
}
}
}Run it with java -Xss256k Depth, then with java -Xss4m Depth. The depth reached grows with the stack size. The exact numbers vary by JVM and by whether the JIT has compiled recurse, so don't rely on them.
Heap exhaustion
import java.util.ArrayList;
import java.util.List;
public class Fill {
public static void main(String[] args) {
List<byte[]> keep = new ArrayList<>();
try {
while (true) {
keep.add(new byte[1024 * 1024]);
}
} catch (OutOfMemoryError e) {
int count = keep.size();
keep = null;
System.out.println("Allocated " + count + " MB before: " + e.getMessage());
}
}
}Run it with java -Xmx32m Fill. The list keeps every array reachable, so the collector cannot reclaim them, and the heap fills. The message is Java heap space. The program stays under 32 MB because the heap also holds other objects and needs room for the collector to work.
Metaspace exhaustion
Metaspace fills when a program defines many classes, for example by creating many class loaders and keeping them reachable. Setting -XX:MaxMetaspaceSize=64m turns a slow leak into an early, visible OutOfMemoryError: Metaspace.
$ java -Xms64m -Xmx512m -Xss512k -XX:MaxMetaspaceSize=128m WhereThis command sets the starting and maximum heap, the per-thread stack size, and the metaspace cap.
Common misconceptions
- "Objects are on the stack." Only references and primitives sit in frames. The objects are on the heap, apart from the JIT's invisible escape-analysis optimization.
- "Static fields live in metaspace." In HotSpot they live in the class's
Classobject on the heap. The class metadata that describes them is in metaspace. - "Metaspace is just PermGen renamed." It lives in native memory, grows on demand, and is cleaned up when class loaders are collected. PermGen was a fixed-size part of the Java heap.
- "The JVM uses only the memory I set with
-Xmx." The process also uses native memory for metaspace, thread stacks, the code cache, the garbage collector's own structures and direct byte buffers. A JVM with-Xmx2gcan use noticeably more than 2 GB of process memory.
Exercise
A service runs with -Xmx1g and creates one new thread per incoming request. After a few thousand concurrent requests it fails with "OutOfMemoryError: unable to create native thread", while heap monitoring shows only 300 MB in use. Which memory area is the problem, and would raising -Xmx help?
Show answer
The problem is thread stacks, which are allocated from native memory outside the heap. Each thread reserves its own stack (about 1 MB by default on 64-bit Linux), so thousands of threads exhaust native memory or the operating system's thread limit. Raising -Xmx would not help and could make it worse by leaving less native memory. Fixes include using a bounded thread pool, lowering -Xss, or reducing the number of concurrent threads.
Exercise
In class Counter, "static int total;" is a field, and main contains "Counter c = new Counter(); int n = 5;". Name the memory area that holds each of: the Counter class's method bytecode, the value of total, the Counter object that c points to, the reference c, and the int n.
Show answer
The method bytecode is in metaspace. The value of total is in the Counter class mirror, a java.lang.Class object on the heap. The Counter object is on the heap. The reference c and the int n are local variables in main's frame on the calling thread's stack.