JVM memory areas
Six areas and six OutOfMemoryErrors, each triggered; Native Memory Tracking explaining a 329 MB process with a 256 MB heap; and what objects cost, from a 16-byte Integer to compressed oops.
"The JVM has a heap" is true and not very useful. A running Java process uses memory in half a dozen distinct areas, each with its own limit, its own failure message, and its own flag — and most memory incidents are someone looking at the wrong one. A service with a 256 MB heap that uses 329 MB of RAM is not leaking. It is a normal JVM, and this lesson shows where the other 73 MB went.
Every output below is from Java 21 on Linux, in a container.
The areas
| area | holds | limited by | shared by |
|---|---|---|---|
| Heap | every object and array | -Xmx | all threads |
| Thread stacks | each thread's frames: locals, operands, return addresses | -Xss per thread, times the number of threads | one per thread |
| Metaspace | class metadata: methods, fields, bytecode, constant pools | -XX:MaxMetaspaceSize (unbounded by default) | all threads |
| Code cache | machine code produced by the JIT | -XX:ReservedCodeCacheSize | all threads |
| Direct memory | ByteBuffer.allocateDirect, used by NIO and network libraries | -XX:MaxDirectMemorySize (defaults to the heap limit) | all threads |
| The JVM itself | GC data structures, symbols, JIT compiler memory, internal buffers | nothing you set directly | — |
The heap is the only one most people configure, and it is only part of the process's footprint.
The specification names two more per-thread areas that turn up in interviews and never in a flag: the PC register, the address of the bytecode instruction the thread is executing (undefined while it is in native code), and the native method stack, the C stack for JNI frames. HotSpot keeps both inside the thread stack it already allocated, so -Xss is the one number that covers them.
Measuring all of them: Native Memory Tracking
The JVM can account for its own memory. Start it with -XX:NativeMemoryTracking=summary and ask a running process with jcmd. A small program with a 256 MB heap limit, 60 MB of live objects, one 32 MB direct buffer and a pool of 50 threads:
$ jcmd <pid> VM.native_memory summary scale=MB
Total: reserved=1834MB, committed=264MB
- Java Heap (reserved=256MB, committed=149MB)
- Class (reserved=1024MB, committed=0MB)
- Thread (reserved=142MB, committed=6MB)
- Code (reserved=242MB, committed=7MB)
- GC (reserved=54MB, committed=51MB)
- Internal (reserved=1MB, committed=1MB)
- Other (reserved=32MB, committed=32MB)
- Symbol (reserved=1MB, committed=1MB)
- Shared class space (reserved=16MB, committed=13MB, readonly=0MB)
- Arena Chunk (reserved=2MB, committed=2MB)
- Metaspace (reserved=64MB, committed=0MB)
process RSS: 329 MBTwo words carry the reading:
- Reserved is address space the JVM has claimed and not necessarily used. It is large and mostly harmless — 1,834 MB here.
- Committed is memory actually backed by RAM. That is the number that counts against a container's limit.
Now the details. The heap has committed 149 MB for 60 MB of live data, because the collector keeps room to work in. The direct buffer is the 32 MB under Other. The GC's own bookkeeping is 51 MB — remembered sets, card tables and marking bitmaps, sized with the heap. And the process's resident size, 329 MB, is larger again than NMT's 264 MB committed, because NMT does not see memory allocated by native libraries through malloc, or the pages of mapped JAR files.
Six ways to run out
Each area fails with its own message, and the message says which limit was hit. Each of these was triggered deliberately:
java.lang.OutOfMemoryError: Java heap space (after 31 allocations)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
java.lang.OutOfMemoryError: Metaspace (after 10550 allocations)
java.lang.OutOfMemoryError: Cannot reserve 1048576 bytes of direct buffer memory (allocated: 67108864, limit: 67108864) (after 64 allocations)
java.lang.StackOverflowError: null
java.lang.OutOfMemoryError: unable to create native thread: possibly out of memory or process/resource limits reached| message | what ran out | the usual cause | the usual fix |
|---|---|---|---|
Java heap space | the heap (-Xmx64m: 31 × 1 MB arrays) | a leak, or a heap too small for the live data | find the leak, or size the heap |
Requested array size exceeds VM limit | nothing yet — the request itself is impossible | a size computed from bad input | validate the size before allocating |
Metaspace | class metadata (MaxMetaspaceSize=32m: about 5,000 generated proxy classes) | a class loader leak, or runaway class generation | find who creates class loaders and never releases them |
Cannot reserve … direct buffer memory | direct memory (MaxDirectMemorySize=64m) | buffers not released, or a limit below what a network library needs | release buffers; size the limit deliberately |
StackOverflowError | one thread's stack (-Xss256k) | unbounded recursion | fix the recursion; raising -Xss only delays it |
unable to create native thread | the operating system's thread or process limit (a container with --pids-limit 400) | an unbounded thread pool | bound the pool |
Only the first is about the heap. Raising -Xmx in response to any of the other five does nothing useful — and for the last one, a bigger heap leaves less memory for thread stacks.
Object layout: what an object really costs
A Java object is not just its fields. Every object has a header — a mark word for locking and GC state, and a pointer to its class — and objects are padded to a multiple of 8 bytes. With default settings on a 64-bit JVM, the header is 12 bytes: an 8-byte mark word and a 4-byte compressed class pointer.
Measured by counting the bytes each allocation added, averaged over a million allocations of each:
default -XX:-UseCompressedOops
new Object() 16 bytes 16 bytes
{ int a; } 16 bytes 16 bytes
{ long a; } 24 bytes 24 bytes
{ int a; Object ref; } 24 bytes 24 bytes
{ Object a, b, c; } 24 bytes 40 bytes
Integer (outside the cache) 16 bytes 16 bytes
new int[0] 16 bytes 16 bytes
new int[10] 56 bytes 56 bytes
new long[10] 96 bytes 96 bytes
new Object[10] 56 bytes 96 bytesReading it:
- An empty object is 16 bytes: the 12-byte header, padded. An
intfits in the padding, so{ int a; }is also 16. - A
longdoes not fit: 12 + 8 = 20, padded to 24. - An
Integeris 16 bytes to hold a 4-byte value. AList<Integer>of a million numbers is about 16 MB ofIntegerobjects plus 4 MB of references, where anint[]of the same numbers is 4 MB. - An array has a 16-byte header (12, plus a 4-byte length), then its elements:
int[10]is 16 + 40 = 56.
Compressed oops store references as 32-bit values that the JVM scales into a heap of up to about 32 GB. Turn them off, or configure a heap above that threshold, and every reference doubles to 8 bytes: three references went from 24 to 40 bytes, and Object[10] from 56 to 96. That is why a heap of 32 GB can hold fewer objects than one of 31 GB, and why heaps just above that size are a known trap.
Stacks, Metaspace and the code cache, briefly
- A thread stack is reserved per thread — the default depends on the platform:
ThreadStackSizeprinted 2040 KB on the ARM64 Linux container used here, and it is 1 MB on x86-64 Linux — and committed as it is used. NMT's 142 MB reserved against 6 MB committed for 50 threads is typical: idle threads use little. Thousands of platform threads still add up, which is part of what virtual threads change. - Metaspace grows with the number of classes loaded, and shrinks only when a class loader becomes unreachable and its classes are unloaded. Frameworks that generate classes — proxies, bytecode enhancers, scripting engines — are where it grows unexpectedly. The class loading lesson covers the loader leak that pins it.
- The code cache holds JIT-compiled code. When it fills, the JVM prints a warning that the compiler has been disabled, and the service keeps running — interpreted, many times slower. The JIT lesson shows how large that difference is.
Under the hood: Metaspace is not "the new PermGen", and why that matters for a redeploy
Before Java 8, class metadata lived in the Permanent Generation — a region inside the heap, sized with -XX:MaxPermSize, collected by the same generational collector as everything else. That made two things true that are no longer true today: PermGen competed with your objects for a fixed slice of -Xmx, and reclaiming a class required the same kind of generational GC cycle that reclaims objects. Application servers that redeployed WARs without restarting routinely filled PermGen, because the collector was conservative about when a class was really eligible for unloading, and java.lang.OutOfMemoryError: PermGen space was one of the most common production errors of that era. JEP 122 removed PermGen in Java 8 and moved class metadata to Metaspace, allocated out of native memory — the same pool malloc draws from, entirely outside the heap named by -Xmx. That is why this lesson's table lists Metaspace as unbounded by default: it grows until it hits -XX:MaxMetaspaceSize (infinite if unset) or the operating system has nothing left to give, not until it hits a heap-relative cap.
Metaspace itself is not one pool. HotSpot splits it into two: class-space, a single reserved region (-XX:CompressedClassSpaceSize, 1 GB by default) that holds compressed class pointers so a compressed oop-style 32-bit reference can still address a class, and non-class space, which holds everything else — method bytecode, constant pools, annotations — and which is what actually grows unbounded. Compressed class pointers only work while class-space has room; once code loads enough distinct classes to exhaust the 1 GB region, the JVM falls back to full 64-bit class pointers for new classes, which is a second, separate failure mode from the Metaspace OutOfMemoryError this lesson already shows — jcmd <pid> VM.native_memory summary breaks the two apart under Metaspace as class space and Metaspace lines when NMT is on. The practical consequence carries straight from the PermGen era into today, just relocated: a class loader leak (the class loading lesson's plugin loaders and the finding memory leaks lesson's classic paths) still fills a bounded region and still throws an OutOfMemoryError — it is no longer competing with your objects for heap space, but it is exactly as fatal, and -XX:MaxMetaspaceSize is worth setting explicitly precisely because "unbounded" on a shared host means "until it takes memory from something else", not "safe".
Try it yourself
Size a container from its parts
A service is deployed with -Xmx1536m in a container with a 2 GiB (2048 MB) memory limit. Production also runs 400 platform threads (a thread-per-request pool sized generously "for safety"), each with the default 1 MB stack on the x86-64 host, plus a Metaspace that typically settles around 150 MB for this codebase, plus a direct-memory-heavy Netty layer that reserves about 64 MB. The container keeps being OOMKilled under load. Using this lesson's table of areas, work out roughly where the ceiling is being hit, and what the one number to change first is.
Where the memory actually went
Add up everything besides the heap: 400 threads × 1 MB = 400 MB of reserved stack space alone (committed is usually far less per idle thread, but under real load with deep call chains it climbs toward reserved), plus roughly 150 MB Metaspace, plus 64 MB direct memory, plus the JVM's own GC bookkeeping (the lesson's NMT example showed 51 MB of GC structures on a 256 MB heap — bookkeeping scales with heap size, so expect tens of MB more on a 1.5 GB heap). That is already 1536 MB (heap) + roughly 400 + 150 + 64 + ~80 = over 2.2 GB, against a 2 GiB limit, before counting the JVM's own internal memory or native library allocations the lesson's NMT table cannot even see. The heap was sized as if it were the only consumer — the same mistake the lesson's -Xmx256m → 329 MB RSS example makes at smaller scale. The single highest-leverage number to change is not the heap: it is the 400-thread pool, since stacks alone account for as much memory as roughly a quarter of the heap. Shrinking the pool to a size actually justified by concurrent load, then re-deriving -Xmx as roughly 70–75% of the container limit as this lesson's PRODUCTION callout recommends, addresses the real ceiling; raising the container's memory limit without addressing the thread count only delays the same failure at a larger number.
Misconceptions
- "Metaspace is just PermGen renamed." It is a genuinely different mechanism: native memory instead of a heap region, an unbounded default instead of a fixed cap, and unloading tied to a class loader becoming unreachable rather than to a generational GC cycle. The failure mode it inherited — a redeploy or a class-generating framework filling it — is the same shape, but the fix (
-XX:MaxMetaspaceSize, not-XX:MaxPermSize) and the diagnosis (native memory tracking, not a heap histogram) are different. - "A
StackOverflowErrormeans the recursion is deep." It usually is, but the actual limit is bytes, not call depth: a recursive method with large local variables or many parameters overflows at a far shallower depth than one with a singleintparameter, so two methods that "look equally recursive" can have very different safe depths on the same-Xss.
Sources
- JEP 122, "Remove the Permanent Generation" (Java 8).
- Oracle, The Java Virtual Machine Specification, SE 21 — §2.5 (Run-Time Data Areas).
java -XX:+PrintFlagsFinaland HotSpot'sCompressedClassSpaceSize/MaxMetaspaceSizedocumentation.