TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท jvm ยท memory ยท performance

JVM memory: heap, stack and metaspace

Where a running Java program keeps things. Each thread has its own stack of frames for local variables, objects live on a shared garbage-collected heap, class metadata lives in native metaspace, and the whole process must fit its container's memory limit.

14 min6 animations

๐Ÿ“š Builds on๐Ÿงน Garbage collection

๐Ÿ–จ๏ธ Cheat sheet

A workshop with three kinds of space

Picture a busy workshop. Every worker, say Ana and Ben, has a workbench of their own. On it they keep the job they're working on right now, and nobody else touches it.

The pieces they make go into one big storeroom that everyone shares. A piece stays there as long as someone might still need it.

And by the wall stands a blueprint cabinet. Before anyone can make their first chair, the chair's blueprint has to be in the cabinet. One blueprint is enough for every chair the workshop will ever make.

Three kinds of space, each with its own job, and each can run out in its own way. Press play to see a first job.

Three memory areas

A running JVM keeps its data in three main areas, each with a different lifetime and owner:

AreaHoldsShared?Freed when
Thread stackOne frame per method call: local variables, parameters, referencesNo, one per threadThe method returns
HeapEvery object and array (new Order()), plus static fields and interned stringsYes, by all threadsThe garbage collector finds it unreachable
MetaspaceClass metadata: the structure, methods and bytecode of each loaded classYesIts class loader is unloaded

Variables on the stack never hold objects, only references to them, so two threads can reach the same heap object. That sharing is why threads need locks, and why each area fails differently: StackOverflowError, OutOfMemoryError: Java heap space and OutOfMemoryError: Metaspace.

Stacks, heap and metaspace5 steps
Ana's workbench0123Ben's workbench0123Storeroom0123Blueprint cabinet0123๐Ÿ‘ฉโ€๐Ÿ”งAna๐Ÿ‘จโ€๐Ÿ”งBen
Press play and watch it happen!

The workbench

When Ana starts a task, she puts a job card on her bench, with the little notes she needs: "3 legs", "oak". If that task needs a smaller task done first, she puts a new card on top and works on that. When the small task is done, she throws its card away and carries on with the one underneath.

So the bench is a pile of cards, and only the top one is being worked on. People call that pile the stack. Notes about big pieces aren't the pieces themselves: a card just says "the chair on shelf 12 in the storeroom".

The bench has a fixed size. If a task keeps asking for the same task again and again without stopping, the pile grows until it falls off the bench, and Ana has to stop.

Thread stacks and frames

Each platform thread gets its own stack, reserved when the thread starts. Every method call pushes a frame holding that call's local variables, parameters and intermediate values; returning pops it. Allocation and release are just a pointer move, so there's nothing for the garbage collector to do here. Virtual threads are different: when unmounted, their frames are kept in heap objects (see virtual threads).

Primitives (int qty = 3) live in the frame itself. For objects, the frame holds only a reference; the object is on the heap. Stack frames are also GC roots: anything a live frame still uses stays alive.

The stack size is fixed per thread: -Xss (or -XX:ThreadStackSize), 1 MiB by default on 64-bit Linux. Recursion that never reaches its base case runs out of room and throws StackOverflowError:

1int depth(Node n) {2    return 1 + depth(n.parent);   // no base case: StackOverflowError3}

Raising -Xss only hides a missing base case. Fix the recursion, or make it a loop. You can also pass a size to one thread with new Thread(group, task, "parser", 8 * 1024 * 1024) (a hint the VM may ignore on some platforms).

Frames on a thread stack6 steps
๐Ÿชš Ana's workbench๐Ÿ‘ฉโ€๐Ÿ”งAna
Press play and watch it happen!

The storeroom

Everything the workers make goes into the shared storeroom, which people call the heap. New pieces land on the arrivals shelf by the door. Most are offcuts and test pieces that nobody needs a minute later, so a tidier clears that shelf often and quickly. The few pieces still wanted after a few clear-outs move to the long-term racks at the back.

The storeroom has a size, set when the workshop opens. If the racks are full of pieces somebody still has a note for, for example a list on the wall that notes every piece ever made and never crosses one off, the tidier can't clear anything, and the next new piece has nowhere to go. Work stops.

A clever worker sometimes notices a piece will never leave their bench: they make it, use it and scrap it in the same task. Then they don't bother sending it to the storeroom at all.

The heap

Every object is allocated on the heap, shared by all threads. Its size is set at startup:

  • -Xms: initial size; -Xmx: maximum size. Production services often set both to the same value to avoid resizing.
  • Without them, the JVM picks defaults from the machine or container memory: -XX:MaxRAMPercentage (default 25%) for the maximum and -XX:InitialRAMPercentage (default 1.5625%) for the start.

Collectors such as G1 (the default on machines with at least 2 CPUs and about 2 GB of memory; smaller containers get Serial GC) split the heap into a young generation, where new objects are allocated and collected often, and an old generation for objects that survive several collections. The garbage collection concept covers how.

When the heap is full of reachable objects and a collection can't free enough, the allocation fails with OutOfMemoryError: Java heap space. The usual cause isn't a too-small heap but a leak: a static map, cache or listener list that keeps references forever. OutOfMemoryError: GC overhead limit exceeded is the same problem caught earlier (thrown by Parallel GC, and by G1 in recent releases), when the JVM spends almost all its time collecting.

๐Ÿ”ง Going deeper

Escape analysis

The JIT compiler (C2) runs escape analysis: if an object never escapes the method that creates it (it isn't returned, stored in a field, or passed to a method the JIT couldn't inline), the compiler can skip the heap allocation entirely and keep its fields in registers or the frame (scalar replacement), and drop locks on it. This only applies to hot, compiled code and is an optimisation, not a guarantee, so don't design around it; it's one reason short-lived small objects are cheaper than they look. It's on by default (-XX:+DoEscapeAnalysis).

The heap fills up5 steps
๐Ÿ“ฆ StoreroomArrivals shelf01234Long-term racks01234๐Ÿ‘ฉโ€๐Ÿ”งAna๐Ÿ‘จโ€๐Ÿ”งBen๐ŸงนTidier
Press play and watch it happen!

The blueprint cabinet

The cabinet, which people call metaspace, gets its blueprints in binders. The workshop's own binder brings the blueprints for its chairs and tables; a plug-in tool might bring its own binder too. A binder can only be thrown out once nothing in the storeroom was made from it and nobody is holding it.

The cabinet doesn't sit in the storeroom. It stands in the workshop's own space, so a full storeroom doesn't fill it, and it can grow until the building has no room left.

Here's the trap. Each time the workshop swaps to a new version of its designs, a new binder arrives. If one old chair is still kept somewhere, the whole old binder has to stay, with every blueprint in it. Swap often enough and the cabinet overflows.

Metaspace

Loading a class stores its metadata (fields, method bytecode, constant pool, JIT profile data) in metaspace. Since Java 8 (JEP 122, which removed the old PermGen), metaspace lives in native memory outside the heap, so -Xmx doesn't bound it. Static fields and interned strings are on the heap.

  • -XX:MaxMetaspaceSize: unlimited by default, bounded only by the process's available memory. Setting it turns unbounded growth into a clear OutOfMemoryError: Metaspace.
  • -XX:CompressedClassSpaceSize: with compressed class pointers, part of the metadata sits in a separate class space (1 GiB reserved by default), which can fail on its own with OutOfMemoryError: Compressed class space.

Metadata is freed only when its class loader becomes unreachable, and a loader stays alive while any class it loaded, or any instance of one, is reachable. That causes class loader leaks on every redeploy or restart that creates a new loader (app servers, plugin systems, Spring Boot DevTools restarts): one leftover reference pins the old loader and all its classes. Typical culprits are a ThreadLocal never removed on a pooled thread, a JDBC driver or shutdown hook registered by the app, or a static cache in a shared library holding an app object. Libraries that generate classes at runtime (proxies, lambdas, scripting) grow metaspace too.

A class loader leak5 steps
Blueprint cabinet012345Storeroom012๐Ÿ“˜ Binder v1๐Ÿ“ List on the wall
Press play and watch it happen!

Renting the workshop

The workshop rents a unit with a fixed floor area. The storeroom isn't the only thing on that floor (everything else is called native memory): there's the blueprint cabinet, every worker's bench, a loading dock for moving goods straight in and out, and a rack of ready-made templates the workshop builds for the jobs it does most, so those go faster.

By default the workshop gives the storeroom only a quarter of the floor, to be safe. Someone who makes the storeroom as big as the whole unit has forgotten everything else. The moment it all spills over the line, the landlord doesn't argue: the workshop is shut on the spot.

Native memory and containers

A JVM process uses much more than the heap. Resident memory is roughly:

AreaBound by
Heap-Xmx
Metaspace and class space-XX:MaxMetaspaceSize, -XX:CompressedClassSpaceSize
Thread stacks-Xss ร— number of platform threads
Code cache (JIT-compiled code)-XX:ReservedCodeCacheSize (240 MiB with tiered compilation)
Direct buffers (ByteBuffer.allocateDirect, NIO, Netty)-XX:MaxDirectMemorySize, by default the max heap size
GC data structures, JIT compiler arenas, symbols, malloc by native librariesMostly nothing

The JVM is container-aware (-XX:+UseContainerSupport, on by default on Linux since JDK 10 and 8u191, with cgroup v2 support from JDK 15, 11.0.16 and 8u372): it reads the cgroup memory and CPU limits, not the host's. So in a Docker container with a 1 GiB limit, the default max heap is 25% of it, 256 MiB.

If the whole process exceeds the limit, the kernel's OOM killer ends it (in Kubernetes, OOMKilled, exit code 137) with no Java exception and no heap dump. Setting -Xmx equal to the container limit makes that likely as soon as the heap grows under load. Prefer a percentage, which follows the limit when it changes:

1java -XX:MaxRAMPercentage=75.0 -jar app.jar

For example, 75% suits a service with little off-heap use; measure resident memory under load, and leave more headroom with many threads, big direct buffers or native libraries. Native failures look different: OutOfMemoryError: Direct buffer memory, or unable to create native thread when threads can't get stacks.

Fitting in a container4 steps
๐Ÿญ Rented unit๐Ÿ“ฆStoreroom๐Ÿ—„๏ธBlueprint cabinet๐ŸชšWorkbenches๐Ÿ“Template rack๐ŸššLoading dock๐Ÿง‘โ€๐Ÿ’ผLandlord
Press play and watch it happen!

Inspecting the workshop

When things go wrong, the manager walks in with a clipboard and asks the workshop questions while it keeps running. "How many pieces of each kind are in the storeroom?" is a quick count.

For a mystery, the manager takes a photo of the whole storeroom (a heap dump), with every note that points at every piece. Back at the desk, they follow the notes backwards to see who is still holding that pile of chairs.

And if the unit is full but the storeroom isn't, the manager measures every area on the floor plan to see which one grew.

Diagnosing memory problems

jcmd <pid> talks to a running JVM:

1jcmd <pid> GC.heap_info                     # heap regions and usage2jcmd <pid> GC.class_histogram               # reachable objects (forces a full GC)3jcmd <pid> GC.heap_dump /tmp/app.hprof      # full heap dump4jcmd <pid> VM.metaspace                     # metaspace by class loader5jcmd <pid> Thread.print                     # every thread's stack6jcmd <pid> VM.native_memory summary         # needs Native Memory Tracking on

A heap dump (.hprof) is a snapshot of every reachable object and reference. Open it in Eclipse MAT or VisualVM and look at the dominator tree and the path to GC roots of the biggest retained sets: that names who holds the leak. Taking a dump pauses the application, the file is about as big as the used heap, and it contains your data (passwords, personal data), so handle it like production data. Capture one automatically on failure:

1java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps \2     -XX:NativeMemoryTracking=summary -jar app.jar

Native Memory Tracking breaks the JVM's own memory into categories (Java Heap, Class, Thread, Code, GC, Internal, and more), with reserved and committed sizes. It must be enabled at startup, costs some performance (around 5 to 10%), and doesn't see memory allocated by native libraries. Take VM.native_memory baseline, wait, then VM.native_memory summary.diff to see what grows. In code, Runtime.getRuntime().maxMemory() and the the memory pool MXBeans (which Spring Boot Actuator exports as jvm.memory.used and jvm.memory.max, tagged by area and pool id) let you watch heap, metaspace and code cache over time; thread stacks and native-library memory aren't included.

Diagnosing with jcmd4 steps
๐Ÿง‘โ€๐Ÿ’ผManager๐ŸญWorkshop
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about JVM memory: heap, stack and metaspace, told the same way as the story.
  1. Ana's card says "the chair on shelf 12". Where is the chair itself?
  2. A task keeps asking for the same task again, forever. What goes wrong?
  3. The workshop keeps switching to new designs, and the cabinet eventually overflows. Why?
  4. The unit is 1,000 square metres and the storeroom is set to 1,000 too. What happens?
Answer every question to check.Passing marks JVM memory: heap, stack and metaspace as done.
Got the hang of JVM memory: heap, stack and metaspace? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

โš™๏ธ Java under the hoodStep 4 of 5

โ† Previous on the path๐Ÿงน Garbage collectionNext on the path โ†’๐Ÿ—ฃ๏ธ JIT compilation

๐Ÿ‘‰ Read next

  • ๐Ÿ—ฃ๏ธJIT compilationA tour guide translating live from a dictionary, who writes the most-asked phrases into a quick phrasebook.