Lesson · JVM Internals
Runtime memory areas: more than the heap
19 min readRuntime Memory Areas
The heap is the biggest area of a JVM process, not the only one. One object's layout (mark word, class pointer, compressed references), then the areas a heap dump never shows: thread stacks, metaspace, the code cache and direct memory. Plus the arithmetic that decides which one kills your container first.
The dump that did not add up
A service in a container gets killed for memory while its heap sits comfortably under -Xmx, and the heap dump it produced shows a small, well-behaved set of objects. The dump is not lying. It is answering a narrower question than the one being asked.
The heap is one area of several. The process also owns a stack per thread, class metadata, the native code the JIT produced, and any buffers your code allocated outside the heap. Five areas, five sets of flags, one process budget:
- Heap: objects and arrays, shared by every thread and managed by the collector. -Xmx sizes it.
- Stacks: one per platform thread, private, fixed in size. -Xss sizes each one.
- Metaspace: class metadata, in native memory, one set per class loader. Capped, if at all, by -XX:MaxMetaspaceSize.
- Code cache: native code produced by the JIT. Bounded by -XX:ReservedCodeCacheSize.
- Direct memory: ByteBuffer.allocateDirect and friends, allocated outside the heap, metered by -XX:MaxDirectMemorySize.
Memory questions are area questions. Heap, stacks, metaspace, code cache and direct memory each have their own failure message and their own tool. Naming the area first is what turns a vague memory problem into a lookup.
Runtime memory areas · who owns what
one process budget, split by ownership and by what a dump can see
per thread
- one per platform thread, private: frames with locals and operand stack
- sized up front by -Xss; a deep recursion throws StackOverflowError, never a heap error
- virtual threads: frames in growable chunk objects on the heap, so -Xss does not size them
shared by all threads
- objects and arrays, managed by the collector
- -Xmx sizes it; the young/old split belongs to the garbage collection part
- the one area a heap dump contains, object by object
Threads share it, so it is also where race conditions live, and it is the only column that gives memory back on its own.
native memory, outside the heap
- class metadata, one set per class loader; released only when that loader is unreachable
- unbounded by default; -XX:MaxMetaspaceSize caps it (-XX:MetaspaceSize is not a cap)
- native code produced by the JIT, bounded by -XX:ReservedCodeCacheSize
- full means compiler disabled and silent interpreter fallback: slower, never an exception
- ByteBuffer.allocateDirect: bytes outside the heap, usable by I/O without copying
- -XX:MaxDirectMemorySize caps it; a Cleaner frees it once the buffer is unreachable
Inset · what one object costs
mark word · 8 B
identity hash (lazy), lock state, collector age
class pointer · 4 B
compressed; leads to the method table
fields, in VM order
arrays add a length field; the VM packs for alignment
pad to 8 B
every object starts at a multiple of 8
Twelve bytes of header plus the fields, rounded up to a multiple of 8. References are 4 bytes while compressed oops are on, which needs the heap to fit under about 32 GB; above that every reference widens to 8 bytes. An object never smaller than 16 bytes is why boxing and object-heavy caches cost what they cost.
A heap dump covers the shared column only. The per-thread and native areas share the same process budget, so a container can die with a heap that looks fine; -XX:NativeMemoryTracking=summary with jcmd prints all of them together.
What one object actually costs
Before any of your fields, every object carries a header the JVM adds. On a typical 64-bit HotSpot with compressed oops: a mark word of 8 bytes, a class pointer of 4, so 12 bytes of header, then your fields, then padding so the whole thing is a multiple of 8 bytes. Two int fields therefore end up as 12 bytes of header plus 8 bytes of data, rounded up to 24.
The mark word is not decoration. It holds the identity hash code once it has been computed (lazily, at the first System.identityHashCode or default hashCode call), the lock state, and collector bookkeeping such as the age of the object. That is why turning an object into a lock leaves a trace in its header.
// dependency: org.openjdk.jol:jol-core (inspection only, never shipped) System.out.println(ClassLayout.parseClass(Point.class).toPrintable()); // class Point { int x; int y; } // OFFSET SIZE TYPE DESCRIPTION VALUE // 0 4 (object header) ... <- mark word, first half // 4 4 (object header) ... <- mark word, second half // 8 4 (object header) ... <- compressed class pointer // 12 4 int Point.x 0 // 16 4 int Point.y 0 // 20 4 (loss due to the next object alignment) // Instance size: 24 bytes // Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
- Mark word (8 bytes): identity hash, lock state, collector age. The hash is written lazily, so a fresh object often has a zero there.
- Class pointer (4 bytes, compressed): which class this is, and through it the method table the runtime dispatches on.
- Fields, then alignment: the VM chooses the field order for size and alignment, not your declaration order; arrays carry an extra length field in the header.
- 8-byte alignment: every object starts at a multiple of 8, so the last few bytes of an awkward size become padding. That alignment is also what makes the next section possible.
Objects are bigger than their fields. A million ints in an int[] pay 4 bytes each plus one header; the same values boxed in a List pay a header per Integer, a reference per element, and the list's own structure on top. Layout is why primitive collections exist and why object-heavy caches surprise people sizing memory.
Compressed oops: why 32 GB looks like a magic number
A reference could be a raw 64-bit address, but that would double the cost of every field and array slot that points at an object. HotSpot keeps references at 32 bits instead, using an alignment fact: objects begin at multiples of 8, so the low three bits of any address are zero and can be left out. A 32-bit reference is treated as a count of 8-byte units, which addresses 4G units, about 32 GB.
Treat the boundary as a guide rather than a cliff with one exact height: alignment options, the address space a VM can map, and the flags in play all nudge it. What matters is the consequence. Past roughly 32 GB, compressed references are no longer possible, every reference widens to 8 bytes, and each object and array grows.
- On by default: HotSpot enables compressed oops and compressed class pointers when the heap fits; -XX:+UseCompressedOops and -XX:-UseCompressedOops override the choice.
- The sizing consequence: a 31 GB heap with 4-byte references can hold more objects than a 33 GB heap with 8-byte ones, which is the origin of the classic keep-it-under-32 GB advice.
- Not a language fact: a reference is still an opaque value that identifies an object (the memory-model-basics lesson, further down the track, calls this layer 2). This is a representation choice, and no program may depend on it.
Compressed oops are why 32 GB is a magic-looking boundary: below it a reference costs 4 bytes, above it 8, so past the boundary the same objects simply need more memory. Sometimes the bigger heap is the smaller budget.
Stacks: one per thread, private, finite
Each platform thread runs on its own stack of frames, and each frame holds the locals, the operand stack and the return information for one call (the bytecode lesson takes the shapes apart). Stacks are private, so nothing on them is shared, and they are sized before the thread starts: -Xss.
Two different failures live here, and merging them is a classic miss. Recursion that runs deeper than the space available throws StackOverflowError on that thread. Running out of room for more stacks, or failing to start a thread at all, surfaces as OutOfMemoryError with a message like unable to create native thread. Thread count multiplied by stack size is the line that kills containers: ten thousand platform threads at 1 MB each reserve 10 GB of stacks before a single object is allocated.
- -Xss sets the size: the default is platform and VM dependent (hundreds of KB up to a MB on 64-bit systems). A deeper recursion budget is bought in native memory, not on the heap.
- A StackOverflowError is per thread: the current thread ran out of its own frame space, and the rest of the process is unaffected.
- Virtual threads change the arithmetic: a virtual thread's frames live in growable chunk objects on the Java heap rather than in a fixed native stack, so they are not sized by -Xss and millions of them do not reserve millions of megabytes. The virtual threads part covers the trade in full.
Stack is per thread and bounded; heap is shared and collected. StackOverflowError is one thread running out of frame space; an OutOfMemoryError about native threads is the process running out of room for more stacks. Different areas, different fixes.
Metaspace: class metadata in native memory
Every loaded class has metadata: field and method descriptors, the bytecode, the constant pool, and the method tables that dispatch and the JIT compile against. Since Java 8 that metadata lives in metaspace, in native memory, one set per class loader (the old PermGen was the previous attempt and it failed because its size was fixed at startup).
Metaspace is unbounded by default: the VM grows it as classes load, limited by the native memory the process can get. -XX:MaxMetaspaceSize caps it. Watch the pair of flags, because they read alike and do different jobs: -XX:MetaspaceSize is not a limit, it is the initial high-water mark that triggers metadata collection and resizing.
- Per loader, freed per loader: metadata belongs to the loader that defined the class and can be released only when that loader is unreachable, the unloading rule from the class-loading lesson.
- Leak symptom: metaspace grows across redeploys while the heap stays flat; the process eventually fails with OutOfMemoryError: Metaspace, and the suspect is whichever pooled thread or registry still points into an old loader.
- Scale: metadata per class is small, from tens of bytes to a few KB, so it takes a lot of generated classes (proxies, frameworks, scripting) to move the number visibly. When it moves, believe it.
Metaspace is native, so the heap flags do not touch it. -Xmx says nothing about it and a heap dump will not show it. A metaspace leak is a class-lifetime question: find what keeps the loader reachable, not what keeps an object alive.
Code cache: where compiled code lives
The JIT writes the native code it produces into the code cache, a native region of its own, bounded by -XX:ReservedCodeCacheSize (a 64-bit server VM picks a default in the low hundreds of megabytes). Compiled methods, their metadata and the stubs the runtime generates all live there.
Running out is quiet in the worst way. When the code cache fills, the compiler stops compiling and prints a warning, and execution falls back to the interpreter. Nothing throws. The program stays correct and simply stops getting faster, which usually shows up as a throughput cliff and a busier CPU rather than as an error anyone can grep for.
- The warning: CodeCache is full. Compiler has been disabled. It is logged once and easy to miss above application noise.
- The diagnosis: jcmd offers code cache statistics, and the warning itself names the fix, raising -XX:ReservedCodeCacheSize.
- When it matters: services with huge numbers of distinct compiled methods (heavy frameworks, generated code) should watch the code cache the way they watch the heap. The JIT lesson covers what fills it.
A full code cache does not stop your program; it stops your program getting faster. The failure is a performance cliff, not an exception, which is why it hides until someone reads the logs or the CPU graph.
Direct memory: allocations outside the heap
ByteBuffer.allocateDirect allocates its bytes outside the heap. The buffer object itself is a small heap object; the storage it refers to is native memory. That is what makes it useful: the operating system can read and write it directly for file and network I/O, without a copy through Java heap memory.
The native block is freed when the buffer becomes unreachable: each direct buffer carries a Cleaner that releases the memory once the buffer object is collected and reference processing runs. Waiting for that to happen under pressure is a common cause of puzzling OOMs. The heap has room for a million small discarded buffers while native memory runs out, and System.gc() only looks like a fix because it happens to trigger reference processing.
# native totals, not just the heap java -XX:NativeMemoryTracking=summary -jar service.jar jcmd <pid> VM.native_memory summary # heap, metaspace, code cache, stacks, direct, and the rest
- Cap it: -XX:MaxDirectMemorySize; when the flag is not set, the limit is derived from the maximum heap size. Exceeding it throws OutOfMemoryError: Direct buffer memory.
- Free it deliberately: ByteBuffer has no close(). Keep direct buffers pooled and long-lived, or move to the foreign function and memory API (MemorySegment with an Arena), which does have an explicit close.
- Dump blind spot: a heap dump contains the small buffer objects and none of their native blocks; memory-mapped files (FileChannel.map) share the property, since their pages belong to the OS page cache.
The heap dump is not the whole memory. It is a faithful picture of one area. When a process dies with a healthy heap, the answer is in metaspace, the code cache, direct buffers or the stacks, and NativeMemoryTracking is the tool that shows them together.
Memory map · one process, five areas
0 MB / 2048 MB
0 MB / 1024 MB
0 MB / 256 MB
0 MB / 240 MB
0 MB / 512 MB
last actionEvery button allocates into one authored meter. Watch which budget grows, and which flag governs it.
Which area answers which question
Match the symptom to the area before opening any tool:
- OutOfMemoryError: Java heap space, or a heap that keeps growing: the heap. A heap dump has the object graph that explains it.
- Metaspace growth across redeploys, eventually OutOfMemoryError: Metaspace: class lifetime. Hunt the reachable loader, not the reachable object.
- Throughput falling with no exception and CPU rising: check for the code cache full warning and the interpreter fallback before blaming the algorithm.
- Container killed while the heap looks small: add up the native side (stacks, metaspace, code cache, direct memory, JVM overhead) with NativeMemoryTracking, because no dump covers it.
- StackOverflowError versus OutOfMemoryError about native threads: one thread ran out of frame space versus the process ran out of room for more stacks. -Xss and thread count are the dials.
Name the area, then pick the tool. Heap: -Xmx and dumps. Metaspace: loaders. Code cache: the warning and jcmd. Direct and stacks: NativeMemoryTracking. The wrong area is why a memory investigation can run all day without meeting the actual consumer.
A heap dump is a picture of the heap only
It is a complete map of one area and a blank one for everything else: metaspace, the code cache, thread stacks and direct buffers are simply not in the file. If a process is dying with a comfortable heap, stop reading the dump and start reading the native totals. The five areas share one process budget, and -Xmx governs exactly one of them.
Interview angles
What is in an object header?+
On a 64-bit HotSpot with compressed oops: an 8-byte mark word (identity hash, lock state, collector age) and a 4-byte compressed class pointer, so 12 bytes before the first field, padded to 8-byte alignment. The smallest objects land at 16 bytes.
The identity hash is not stored until it is needed, and it is not the same as a user-defined hashCode. Lock state lives in the header too, which is why locking has no separate structure per object until it is contended.
Common misconception: That the header is an implementation detail with no observable consequences. Object size, cache footprint and the cost of boxing are all read off the layout.
What are compressed oops, and where does the 32 GB figure come from?+
HotSpot stores references as 32-bit values when it can. Because objects are 8-byte aligned, the value is treated as a count of 8-byte units, addressing up to about 32 GB. Beyond that, references widen to 8 bytes and objects grow.
The limit is a consequence of alignment plus the 32-bit size, not a hard rule of the language: VM configuration and address layout can shift it, so treat 32 GB as the guide and remember the effect rather than an exact threshold.
Common misconception: That a bigger heap always reduces memory pressure. Crossing the boundary widens every reference, so the same object graph needs more memory than it did at 31 GB.
StackOverflowError and OutOfMemoryError: how do you tell the two apart?+
StackOverflowError means one thread exhausted its own frame space, almost always runaway recursion. OutOfMemoryError means an allocation failed: heap space, metaspace, direct buffer memory, or unable to create native thread when a new stack cannot be reserved.
Each OOM message names its area, which is half the diagnosis: Java heap space, Metaspace, Direct buffer memory, unable to create native thread. StackOverflowError is per thread by definition and leaves the rest of the process running.
// each failure names its area java.lang.StackOverflowError // this thread's stack ran out java.lang.OutOfMemoryError: Java heap space // heap exhausted java.lang.OutOfMemoryError: Metaspace // class metadata, loader-held java.lang.OutOfMemoryError: Direct buffer memory // native buffers over the cap java.lang.OutOfMemoryError: unable to create native thread // stacks, thread count
Why can a container be killed while the heap looks healthy?+
Because the heap is one area of the process. Metaspace, code cache, direct memory, thread stacks and JVM overhead all count against the container limit, and none of them appear in a heap dump.
The classic combination: a few thousand threads at 1 MB of stack each, direct buffers waiting for a Cleaner, metaspace held by an old loader, and a code cache that grew after a framework update. NMT prints the breakdown.
Follow-up: How would you prove which of those is the one growing?
When is direct buffer memory returned to the operating system?+
When the buffer object becomes unreachable and its Cleaner runs, which happens during reference processing after a collection. Until then the native block is held even though the Java object is no longer referenced.
This is why a program can look tidy in the heap and still exhaust native memory: the discarded buffers are tiny objects, and their bytes are invisible to the heap meter. A common pattern is to rely on System.gc() to force the timing, which is a symptom, not a design.
Common misconception: That setting the buffer reference to null frees the memory immediately. It removes one path; the native block is released later, by the Cleaner.
What happens when the code cache fills up?+
The JVM stops compiling and logs a warning; execution falls back to the interpreter. Nothing throws, so the visible symptom is a throughput drop with CPU spent in interpreted code.
The cache is sized by -XX:ReservedCodeCacheSize, and the fix is raising it, not clearing it at run time. It matters most for programs that generate or load enormous numbers of methods.
Follow-up: Why does an interpreter fallback show up as higher CPU rather than as an error?