BE·40
JVM Internals and Other Runtimes
What happens between `java -jar` and your code running fast. Covers bytecode and the stack machine, class loading, class loaders and verification, runtime data areas (heap, stacks, metaspace), interpretation and tiered JIT compilation, inlining, deoptimisation, safepoints, and garbage collection from first principles through Serial, Parallel, G1, ZGC and Shenandoah, with pause time, throughput, allocation rate and heap sizing. Compared with the CLR, Go's runtime, V8, CPython, BEAM, GraalVM native image, and the no-runtime languages (C, C++, Rust, Zig).
Start here: what happens when you run java
Three jobs
When you run java -cp out Basics, the Java Virtual Machine (JVM) does three jobs that C, Rust and Go programs do before they ship and that Python and JavaScript do in their own runtimes:
- Loads classes when they're first needed, checks the bytecode is safe, and sets them up.
- Executes the bytecode: first by interpreting it, then by compiling the busy parts to native machine code while the program runs (just-in-time, or JIT, compilation).
- Manages memory: you create objects with
new, and the garbage collector (GC) finds objects nothing refers to any more and reclaims their space.
One small program shows all three:
static class Tax { static { System.out.println(" (Tax class loaded and initialised now)"); } static int gst(int p) { return p * 5 / 100; } }
static int total(int pricePaise, int qty) { int sub = pricePaise * qty; return sub + Tax.gst(sub); }
System.out.println("main started; Tax not loaded yet");
System.out.println("total for 2 × ₹90: " + total(9000, 2) + " paise");
for (int round = 1; round <= 6; round++) { … time 200,000 calls of total(…) … }
main started; Tax not loaded yet
(Tax class loaded and initialised now)
total for 2 × ₹90: 18900 paise
round 1: 4.52 ms
round 2: 0.73 ms
round 3: 0.68 ms
…
round 6: 0.66 ms
heap: max 1496 MB, cores 2, GC [G1 Young Generation, G1 Concurrent GC, G1 Old Generation]
Job 1: loading classes lazily
Tax wasn't loaded when the program started; the JVM loaded it the first time total called Tax.gst, and ran its static { } initialiser at that moment. Classes are found by class loaders (the JDK's own, then your classpath or modules), verified (the bytecode can't corrupt memory or break type rules) and linked. This laziness is why Java programs start quickly enough despite thousands of library classes, and why a missing JAR shows up as a NoClassDefFoundError only when the code path that needs it first runs, perhaps hours after startup.
Job 2: from bytecode to machine code
Here's what javac produced for total, shown with javap -c:
static int total(int, int);
0: iload_0 // push pricePaise
1: iload_1 // push qty
2: imul // multiply the top two
3: istore_2 // store in local 2 (sub)
4: iload_2
5: iload_2
6: invokestatic #7 // Method Basics$Tax.gst:(I)I
9: iadd
10: ireturn
Bytecode is a simple stack machine language: instructions push values, operate on the top of the stack and store results. The JVM starts by interpreting it, one instruction at a time, which is slow. It counts how often each method runs; hot methods are compiled by the fast C1 compiler, then, with the profile gathered meanwhile, by the optimising C2 compiler (or Graal). That's the warm-up in the timings: round 1 took 4.5 ms, and from round 2 the compiled code took about 0.7 ms, about 6× faster. The optimiser can do things an ahead-of-time compiler can't, such as inlining Tax.gst into total because it saw that's the only implementation ever called, and undoing that (deoptimising) if a new class changes the picture.
Warm-up is why the first requests after a deploy are slow, why benchmarks must discard early iterations (chapter 41), and why serverless functions and CLI tools care about alternatives: the AOT cache (chapter 39) and GraalVM native images (chapter 42).
Job 3: garbage collection
Every new takes memory from the heap; local variables and call frames live on each thread's stack (Volume 1 chapter 7). The garbage collector periodically finds objects still reachable from the program's roots (stack variables, static fields) and reclaims everything else. Most objects die young (a request's temporary objects), so collectors split the heap into generations: a young area collected often and cheaply, and an old area for long-lived data.
Collection needs the application paused at least briefly. The JVM ships several collectors trading throughput (total work done) against pause times: G1, the default and a good balance (the program above used it); Parallel for batch throughput; ZGC for sub-millisecond pauses at large heaps; Serial for tiny containers. The lab ran one workload under all four.
Compared with other runtimes
| Runtime | Compilation | Memory |
|---|---|---|
| JVM (Java, Kotlin, Scala) | Interpreter + tiered JIT; AOT options | Tracing, generational GC; several collectors |
| .NET (C#) | Tiered JIT; ReadyToRun and Native AOT | Generational GC |
| Go | Ahead-of-time to native | Concurrent, non-generational GC, low pauses |
| Rust, C, C++, Zig | Ahead-of-time to native | No GC: ownership, RAII or manual |
| CPython | Bytecode interpreter (experimental JIT in 3.13+) | Reference counting plus cycle collector |
| Node.js (V8) | Interpreter + optimising JITs | Generational GC |
How deep to go in JVM internals
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain class loading, bytecode, the JIT and garbage collection in a sentence each |
| L2 | Read javap output, recognise warm-up, choose a collector and heap size |
| L3 | Explain tiered compilation, inlining, deoptimisation, safepoints, class loader delegation, and how each GC works |
| L4 | Diagnose warm-up, megamorphic calls, GC pauses and class loading failures from logs and JFR |
| L5 | Tune a service's runtime (GC, heap, container limits, AOT cache) from measurements |
| L6 | Set runtime standards (JDK distribution, GC defaults, observability flags) across a fleet |
Runtimes, from no runtime to a full VM
The spectrum
| Runtime style | Languages | What runs | Memory management |
|---|---|---|---|
| No runtime (beyond a tiny startup and libc) | C, C++, Rust, Zig | Native machine code, compiled ahead of time | Manual (C), RAII/ownership (C++, Rust), explicit allocators (Zig) |
| Native code + language runtime | Go, Swift, Haskell (GHC), OCaml, Nim | Native code linked with a runtime: scheduler and GC (Go), ARC (Swift) | GC (Go, OCaml, Haskell), reference counting (Swift) |
| Managed VM with JIT | Java/Kotlin/Scala (JVM), C#/F# (CLR), JavaScript (V8, SpiderMonkey, JSC) | Bytecode or IL, interpreted then JIT-compiled to native code using runtime profiles | Tracing GC |
| Interpreter (with an optional JIT) | CPython, Ruby (YJIT), PHP (JIT since 8), Lua (LuaJIT) | Bytecode interpreted; JITs are newer additions | Reference counting + cycle collector (CPython), GC |
| Actor VM | Erlang/Elixir (BEAM) | Bytecode; the JIT (BeamAsm, OTP 24+) emits native code at load time | Per-process heaps, GC'd independently |
The JVM's bet, made in 1995 and refined since, is that a profile-guided JIT can produce faster code than a static compiler for long-running server processes, because it optimises for the actual types, branches and call targets observed at run time. Its costs are startup time, warmup and memory overhead. Much of the JVM's recent work (CDS, the AOT cache, GraalVM native image) attacks exactly those costs.
The life of a Java program
Bytecode
The JVM as a stack machine
javac doesn't produce machine code. It produces bytecode: compact instructions for an abstract stack machine. Each method frame has a local variable array and an operand stack. Instructions push operands, pop them, compute, and push results. A stack machine makes bytecode compact and easy to verify and JIT-compile, and keeps it independent of how many registers a real CPU has.
public final class Calc {
static int add(int a, int b) { return a + b; }
int scaled(int x) { return x * factor + 1; }
private int factor = 3;
}
$ javac Calc.java && javap -c -p Calc
static int add(int, int);
Code:
0: iload_0 // push local 0 (a)
1: iload_1 // push local 1 (b)
2: iadd // pop two ints, push the sum
3: ireturn // return the int on top of the stack
int scaled(int);
Code:
0: iload_1 // x (local 0 is 'this' in instance methods)
1: aload_0 // this
2: getfield #7 // Field factor:I (#7 = constant pool entry)
5: imul
6: iconst_1
7: iadd
8: ireturn
Things to notice:
- Instructions are typed (
iaddfor ints,laddfor longs,daddfor doubles,aloadfor references). The verifier relies on that. - Symbolic references (
#7) point into the constant pool, a per-class table of names, types, strings and method references. They're resolved lazily at first use, which is how Java links at run time. - Method invocation comes in five instructions:
invokestatic,invokevirtual(class methods, virtual dispatch),invokeinterface,invokespecial(constructors, private and super calls), andinvokedynamic(JDK 7), whose call-site behaviour is decided at run time by a bootstrap method.invokedynamicpowers lambdas, string concatenation (StringConcatFactory), records'toString/equals/hashCode(ObjectMethods), pattern-matching switch (SwitchBootstraps), and the dynamic languages on the JVM. - The class file format carries the bytecode plus metadata: fields, methods, generic signatures, annotations, line number tables (for stack traces), local variable tables (with
-g), andStackMapTableframes that speed up verification. The Class-File API (JDK 24) is the JDK's own library for reading and writing class files, replacing the internal copy of ASM.
Other intermediate representations:
| Platform | IR | Notes |
|---|---|---|
| JVM | Stack bytecode | Also targeted by Kotlin, Scala, Groovy, Clojure |
| .NET CLR | CIL/MSIL, also a stack machine | Generics are reified in IL. Assemblies carry rich metadata |
| WebAssembly | Stack-based binary format | Structured control flow, validated in a single pass |
| CPython | Bytecode (dis module) |
Interpreted. 3.11+ has an adaptive specialising interpreter; 3.13+ an experimental copy-and-patch JIT |
| BEAM | BEAM bytecode | JIT-compiled at load time (BeamAsm) |
| LLVM (Rust, Swift, Clang, Zig's LLVM backend) | LLVM IR, an SSA register-based form | Compiler-internal, not shipped (except as bitcode in some cases) |
| Go | Internal SSA IR | Compiled to native code ahead of time; no portable IR is shipped |
Classes at run time
Class loading
A class is loaded on demand the first time it's actively used, not at startup. The process has three phases:
- Loading: a class loader finds the bytes (from a JAR, the module image, the network, or generated in memory) and creates a
Classobject plus internal metadata in metaspace. - Linking: - Verification: checks that the bytecode is well formed and type-safe (below). - Preparation: allocates static fields with default values (0, null, false). - Resolution: turns symbolic constant-pool references into direct ones. This is lazy in HotSpot, happening on first execution of each instruction.
- Initialisation: runs the static initialisers (
static {}blocks and static field initialisers) exactly once, under a lock, the first time the class is actively used (anew, a static method call, or a static non-constant field access). That's why the holder idiom (chapter 38) gives thread-safe lazy singletons for free.
Consequences you'll meet:
ClassNotFoundException: explicit loading (Class.forName,loadClass) didn't find the class.NoClassDefFoundError: the class was present at compile time but can't be loaded now. Common causes are a missing JAR or a static initialiser that failed earlier (the first failure is anExceptionInInitializerError, and later attempts getNoClassDefFoundError: Could not initialize class X).NoSuchMethodError/IncompatibleClassChangeError: binary incompatibility. Code was compiled against one version of a library and runs with another (a dependency conflict, chapter 42).- Startup cost: a Spring Boot application loads 10,000–20,000 classes. Each one is parsed, verified and linked. CDS and the AOT cache archive this work.
Class loaders
Class loaders form a delegation hierarchy:
| Loader | Loads |
|---|---|
| Bootstrap (native, in the JVM) | Core platform modules (java.base…) |
| Platform (was "extension" before 9) | Other Java SE and JDK modules |
| Application (system) | The class path / module path: your code and libraries |
| Custom loaders | Whatever they decide: application servers (one per WAR), plugin systems, Spring Boot's LaunchedClassLoader for nested JARs, hot reload (Spring DevTools' restart loader), OSGi bundles |
Parent-first delegation: a loader asks its parent first and loads the class itself only if the parent can't. This guarantees that java.lang.String always comes from the bootstrap loader, so nobody can substitute a malicious String. Some containers (Tomcat's web-app loader) deliberately use child-first loading so each web app can bundle its own library versions.
A class's run-time identity is (fully qualified name, defining class loader). The same class loaded by two loaders gives two distinct, incompatible types, which produces the classic confusing error ClassCastException: com.acme.Foo cannot be cast to com.acme.Foo. It also explains class loader leaks (metaspace growth on redeploy): a ThreadLocal, static cache, JDBC driver registration or running thread that references an old web app's classes keeps its whole class loader, and every class it loaded, alive.
ClassLoader cl = Order.class.getClassLoader(); // app loader
ClassLoader tccl = Thread.currentThread().getContextClassLoader(); // used by ServiceLoader, JNDI, frameworks
// Frameworks that load user classes (Jackson, Hibernate, JAXB) consult the thread context class loader,
// which is why it matters in app servers, test runners and Spring Boot's fat JARs.
There's no equivalent in AOT-compiled languages. Go, Rust, C++ and Zig link everything at build time (static linking by default for Go, Rust and Zig) or rely on the OS dynamic loader (.so/.dll loading, with dlopen for plugins). .NET has AssemblyLoadContext, the CLR's analogue with similar isolation and unloading semantics.
Verification
The bytecode verifier proves, before code runs, that it can't break the JVM's safety: no stack overflow or underflow within a frame, operand types always match instructions (no treating an int as a reference, which would forge pointers), no jumps outside the method or into the middle of an instruction, objects initialised before use, private and final respected, and so on. Since Java 6/7 the type-checking verifier uses the StackMapTable frames that javac emits, making verification a fast single linear pass.
This is why the JVM can load untrusted bytecode and why JVM languages stay memory-safe. WebAssembly validation applies the same idea. Native code has no equivalent: a C binary can do anything its process permissions allow. Classes loaded by the bootstrap loader skip verification by default, since they're trusted.
Memory layout
Runtime data areas
| Area | Shared? | Holds | Error when exhausted |
|---|---|---|---|
| Heap | All threads | Every object and array | OutOfMemoryError: Java heap space / GC overhead limit exceeded |
| Metaspace (native, since 8; replaced PermGen) | All threads | Class metadata, method bytecode, constant pools, JIT profiles | OutOfMemoryError: Metaspace (class loader leaks, runaway proxy generation) |
| Code cache | All threads | JIT-compiled native code | A warning, then the JIT stops compiling: a silent slowdown |
| JVM stacks | Per thread | Frames: local variables, operand stacks, return addresses | StackOverflowError (deep recursion) |
| PC register / native stack | Per thread | Current instruction; frames of native methods | — |
| Direct / native memory | — | ByteBuffer.allocateDirect, Netty buffers, FFM arenas, GC data structures, thread stacks |
OutOfMemoryError: Direct buffer memory, or the container OOM-killer |
Container memory pitfall: process RSS = heap + metaspace + code cache + thread stacks + GC overhead + direct buffers + JVM internals. A pod with memory: 1Gi and -Xmx1g will be OOM-killed. Typical guidance: -XX:MaxRAMPercentage=75 (or less with heavy off-heap use) and Native Memory Tracking (-XX:NativeMemoryTracking=summary, then jcmd <pid> VM.native_memory) to see where native memory goes (chapter 41).
Objects on the heap
A HotSpot object is a header plus fields, padded to 8-byte alignment:
- Mark word (8 bytes): identity hash code, GC age, and lock state (thin or inflated locks).
- Class pointer (4 bytes with compressed class pointers): the object's
Klass. - Arrays add a 4-byte length.
- Compact object headers (product in JDK 25, default in JDK 27) merge these into a single 8-byte header.
- Compressed oops: with heaps under about 32 GB, references are 32-bit offsets scaled by 8, halving pointer size. Crossing ~32 GB loses this, so a 33 GB heap can hold fewer objects than a 31 GB one.
Chapter 41 goes deeper into layout, escape analysis and measurement.
Execution: interpreter and JIT
Tiered compilation
HotSpot starts every method in the interpreter (a fast template interpreter generated at startup), counting invocations and loop back-edges. Hot code climbs through the tiers:
| Tier | Compiler | What it does |
|---|---|---|
| 0 | Interpreter | Executes bytecode, collects basic counts |
| 1 | C1 | Fully optimised C1 code with no profiling, for trivial methods |
| 2 | C1 | Limited profiling |
| 3 | C1 | Full profiling: receiver types at call sites, branch frequencies, null checks seen |
| 4 | C2 | Aggressive optimisation using the profile: speculative inlining, devirtualisation, escape analysis, loop unrolling, vectorisation (auto-SIMD), lock elision |
The usual path is 0 → 3 → 4. C1 compiles fast and gives decent code quickly, while C2 takes longer and produces much faster code for the methods that matter. Thresholds are in the thousands of invocations, which is why JVM services need warmup: the first requests run slower, latency stabilises after the hot paths reach tier 4, and benchmarks must include a warmup phase (JMH handles this, chapter 41).
The Graal JIT (written in Java) can replace C2. It's the basis of GraalVM's JIT mode and of Oracle's investments in the JIT space.
Inlining: the mother of all optimisations
Inlining replaces a call with the callee's body. That removes call overhead, but more importantly it exposes the combined code to further optimisation: constant folding across the boundary, eliminating redundant null checks, escape analysis of objects passed into the callee, and so on. HotSpot inlines small methods (up to about 35 bytes of bytecode, or 325 bytes if hot) and, crucially, virtual and interface calls, speculatively:
- Class hierarchy analysis (CHA): if only one loaded class implements a method, a call through the interface can be inlined directly. If a second implementation is loaded later, the compiled code is invalidated.
- Inline caches and type profiles: if a call site has only seen
ArrayList(monomorphic) or two types (bimorphic), C2 inlines them behind a cheap type check (a "guard"). If an unseen type shows up, the guard fails and triggers an uncommon trap. - Megamorphic call sites (three or more observed types) fall back to a vtable or itable dispatch with no inlining. That's why "one generic method called with many lambdas" (
Stream.mapacross a whole application) can be slower than you'd expect.
This is how Java's "every method is virtual" design costs almost nothing in hot code, and why the JIT can beat a static compiler that has to assume any implementation might arrive.
Deoptimisation
C2's speculation needs an escape hatch. Deoptimisation discards compiled code whose assumptions no longer hold and transfers the running frames back to the interpreter, rebuilding interpreter frames from the optimised frame's state using debug information recorded at compile time. Triggers:
- An uncommon trap: a type, branch or null that the profile said never happened.
- Class loading invalidating a CHA assumption (a new subclass appears).
- Redefinition of classes by agents or debuggers.
The method is then reprofiled and possibly recompiled with the new information. Pathological deopt storms (code that keeps flipping types) appear in JFR as jdk.Deoptimization events. In -XX:+PrintCompilation output, they show as "made not entrant".
On-stack replacement (OSR): a long-running loop in a method that's only called once (say, main running a loop for an hour) gets compiled while it's running, and execution jumps into the compiled loop mid-iteration.
Safepoints
Some JVM operations need every Java thread stopped at a known state, where the JVM knows exactly which stack slots and registers hold object references: certain GC phases, deoptimisation, class redefinition, biased-lock revocation (biased locking was removed in JDK 18), and some thread-dump operations. Threads stop at safepoints: polling locations in compiled code (method returns and loop back-edges) and between bytecodes in the interpreter.
- Time-to-safepoint (TTSP) is the delay between requesting a safepoint and the last thread arriving. A thread in a long counted loop (an
intloop the JIT optimised without safepoint polls) could delay a pause for hundreds of milliseconds. Modern HotSpot uses loop strip mining to insert polls periodically. - Most JVM operations now use thread-local handshakes (JDK 10) to stop individual threads rather than all of them.
- Diagnose with
-Xlog:safepoint(time to reach, and time spent at, each safepoint).
Go has a similar concept: asynchronous preemption uses signals to stop goroutines at safe points for GC and scheduling. Native languages without GC need none of this.
Other runtimes' execution strategies
| Runtime | Execution | Notes |
|---|---|---|
| .NET CLR | Tiered JIT (RyuJIT): tier 0 quick JIT, tier 1 optimised, plus dynamic PGO (default since .NET 8) | Native AOT (no JIT, like GraalVM native image) and ReadyToRun (precompiled code plus JIT) |
| V8 (Node.js) | Ignition interpreter → Sparkplug (baseline) → Maglev (mid-tier optimiser) → TurboFan (top tier) | Hidden classes and inline caches give dynamic JS objects fast property access. Deoptimises on shape changes |
| CPython | Bytecode interpreter; specialising adaptive interpreter (3.11) gave 10–60% speedups; experimental copy-and-patch JIT (3.13+) | Much slower than JIT VMs for pure-Python code; performance comes from C extensions (NumPy) |
| PyPy | Tracing JIT | Often several times faster than CPython; weaker C-extension compatibility |
| BEAM | BeamAsm JIT at load time (OTP 24+) | Optimised for many small processes, not raw compute |
| Go | AOT only: a fast compiler, modest optimisation (inlining, escape analysis), profile-guided optimisation from a production CPU profile (default.pgo, Go 1.21+) |
Instant startup and predictable performance; no warmup and no speculation |
| Rust, C++, Zig, C | AOT through LLVM (or Zig's own backend) with heavy optimisation (-O2/-O3, LTO, PGO via -fprofile-use or BOLT) |
No warmup. The optimiser must be conservative about what it can't prove (aliasing, call targets) |
GraalVM Native Image brings AOT to Java. It runs a closed-world static analysis from main (only reachable code and classes are included), initialises some classes at build time, and emits a standalone native executable with a small runtime (Substrate VM: GC, threads). The results are about 10× faster startup (tens of milliseconds) and much lower memory, which suits serverless and CLI tools. The costs: no JIT speculation (peak throughput is typically lower unless you use PGO), long build times, and reflection, proxies, resources and serialisation must be declared (reachability metadata), which is why Spring Boot generates it with its AOT engine (chapter 47). Project Leyden (the JDK's AOT cache) is the middle path: keep the JIT and full dynamism, but ship pre-loaded, pre-linked classes, profiles and eventually compiled code from a training run.
Garbage collection
Garbage collection from first principles
A garbage collector automatically reclaims memory occupied by objects the program can no longer reach. "Reachable" means reachable by following references from the GC roots: local variables and operand stacks of every thread's frames, static fields, JNI references, and some JVM internals.
The fundamental algorithms:
| Algorithm | How | Pros | Cons |
|---|---|---|---|
| Reference counting | Each object counts incoming references; free at zero | Immediate, incremental reclamation | Can't collect cycles without extra machinery; count updates are costly, especially atomic ones under concurrency |
| Mark-sweep | Mark everything reachable from the roots, then sweep unmarked objects into free lists | Simple, non-moving | Fragmentation; sweep cost is proportional to heap size |
| Mark-compact | Mark, then slide live objects together | No fragmentation; bump-pointer allocation afterwards | Multiple passes over the heap |
| Copying (semispace) | Copy live objects from "from-space" into "to-space", then flip | Cost is proportional to live data, not heap size; compacts automatically | Needs reserve space; copying large live sets is expensive |
The generational hypothesis: most objects die young. A request's DTOs, iterators, lambdas and temporary strings are typically dead within milliseconds. So split the heap:
- A young generation collected frequently with copying. Its cost is proportional to the few survivors, so collecting a mostly dead region is cheap.
- An old generation for objects that survive several young collections (promotion, or tenuring), collected rarely.
- A write barrier (code emitted on every reference store) records old→young pointers in a card table or remembered set, so a young collection doesn't have to scan the whole old generation to find roots.
Allocation in the JVM is extremely cheap. Each thread has a TLAB (thread-local allocation buffer) in eden, and allocating an object is a pointer bump plus header initialisation (about 10 instructions). That's faster than malloc in most C libraries. The cost of allocation shows up later as GC work, proportional to the allocation rate.
The metrics that matter
- Pause time (latency): how long application threads are stopped (stop-the-world, STW). It drives tail latency (p99, p999).
- Throughput: the fraction of CPU time spent running the application rather than GC. For example, 99% throughput means 1% GC overhead.
- Footprint: extra memory the collector needs (headroom, remembered sets, forwarding tables).
- Allocation rate: MB/s of new objects, the main driver of young-GC frequency.
- Promotion rate and live set size: what survives, which drives old-generation work.
You can't optimise all three of pause time, throughput and footprint at once. Concurrent collectors cut pauses by doing work alongside the application, which costs CPU (throughput) and memory (headroom). That's the GC trilemma.
HotSpot's collectors
| Collector | Flag | Design | Use when |
|---|---|---|---|
| Serial | -XX:+UseSerialGC |
Single-threaded, STW, generational (copying young, mark-compact old) | Tiny heaps (< ~100 MB), one CPU, small containers, CLIs |
| Parallel | -XX:+UseParallelGC |
Like Serial but multi-threaded STW phases | Throughput matters and pauses don't: batch jobs, offline processing |
| G1 (Garbage-First), the default | -XX:+UseG1GC |
Heap split into equal regions (1–32 MB). Young collections evacuate eden and survivor regions (STW, parallel). Concurrent marking finds live data in the old generation, then mixed collections evacuate the old regions with the most garbage first (hence the name). Aims for a pause-time goal (-XX:MaxGCPauseMillis=200 by default). Humongous objects (≥ half a region) get dedicated regions |
General-purpose servers. Balanced latency and throughput, heaps from hundreds of MB to tens of GB |
| ZGC | -XX:+UseZGC (generational since 21, the only mode since 24) |
Concurrent marking, relocation and compaction. Coloured pointers (metadata bits in references) plus load barriers: when the app loads a reference to an object being moved, the barrier fixes it ("self-healing"). STW pauses stay under 1 ms regardless of heap size (up to 16 TB) | Low-latency services, large heaps, tight p99/p999 SLOs |
| Shenandoah | -XX:+UseShenandoahGC (generational mode a product option since 25) |
Concurrent compaction using forwarding pointers and load-reference barriers (developed by Red Hat). Pauses usually a millisecond or less | Low latency; available in most OpenJDK builds (not Oracle's) |
| Epsilon | -XX:+UseEpsilonGC |
No-op: allocates and never collects | Performance testing, very short-lived jobs |
Choosing:
- Start with the default (G1) and correct heap sizing. Most "GC problems" are allocation or sizing problems.
- If tail latency from GC pauses violates your SLO and you can afford roughly 10–20% more CPU and some memory headroom, try generational ZGC.
- For batch throughput, try Parallel.
- In tiny containers (≤ 1 CPU, small heaps), the JVM's ergonomics historically picked Serial. JDK 27's JEP 523 makes G1 the default in all environments, so set Serial explicitly where it wins.
Reading GC logs
$ java -Xlog:gc*:file=gc.log:time,uptime,level,tags -Xms2g -Xmx2g -XX:+UseG1GC -jar app.jar
[12.345s][info][gc] GC(41) Pause Young (Normal) (G1 Evacuation Pause) 1210M->312M(2048M) 8.912ms
[30.001s][info][gc] GC(57) Pause Young (Concurrent Start) (G1 Humongous Allocation) 1650M->702M(2048M) 11.4ms
[30.210s][info][gc] GC(58) Concurrent Mark Cycle 205.3ms
[31.002s][info][gc] GC(59) Pause Young (Mixed) (G1 Evacuation Pause) 1100M->540M(2048M) 14.0ms
Read: heap before → after (committed), and pause duration. Healthy G1 shows frequent short young pauses with occupancy after GC (≈ the live set) staying flat. Warning signs:
- Occupancy after GC keeps climbing → a memory leak (heap dump time, chapter 41).
Pause Full (G1 Compaction)→ G1 fell back to a full STW compaction: the heap is too small, or a leak, or promotion failure.To-space exhausted/ evacuation failure → not enough free regions to copy into.- Humongous allocations → huge arrays (big byte buffers, large JSON strings). Consider a larger
-XX:G1HeapRegionSizeor streaming instead. - For ZGC, "Allocation Stall" → the app allocates faster than ZGC can reclaim concurrently. Add heap headroom or reduce allocation.
Tools: GCeasy, GCViewer, and JDK Mission Control's GC views on JFR recordings.
Heap sizing
-Xms=-Xmxin servers (or-XX:InitialRAMPercentage=MaxRAMPercentagein containers): avoids resize pauses and makes behaviour predictable. JDK ergonomics can uncommit unused memory, but predictability usually wins for services.- Size to the live set: run under realistic load, find the old-generation occupancy right after a full or mixed collection (the live set), and give the heap about 3–4× the live set for G1 (more for concurrent collectors, which need headroom to keep running while the app allocates).
- A bigger heap means fewer collections for generational and copying collectors (cost proportional to live data). For G1 it doesn't directly lengthen young pauses, but it does make full GCs (if they happen) catastrophic.
- Containers:
-XX:MaxRAMPercentage=75and-XX:+ExitOnOutOfMemoryError(let the orchestrator restart a broken JVM instead of limping on), plus-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps. - Reduce allocation before tuning flags: the cheapest GC is the one that never runs (chapter 41).
Garbage collection in other languages
| Language | Memory management | Characteristics |
|---|---|---|
| Go | Concurrent, non-moving, non-generational tri-colour mark-sweep with a write barrier. "Green Tea" (experimental in 1.25, enabled by default in 1.26) improves locality by scanning memory in spans | Very short STW pauses (well under 1 ms). Tuned by GOGC (heap growth percentage, default 100) and GOMEMLIMIT (soft memory cap, 1.19+, important in containers). Non-moving means fragmentation is managed by size-class allocation. Escape analysis keeps many values on the stack |
| .NET | Generational (gen0/1/2 + a large object heap), compacting; Workstation vs Server GC, background GC; DATAS (dynamic adaptation) default for Server GC in .NET 9 | Similar trade-offs to the JVM; structs and Span<T> reduce allocation |
| V8 | Generational: Scavenger (parallel copying) for the young generation; Orinoco concurrent and incremental mark-compact for the old generation | Pauses tuned for UI responsiveness |
| CPython | Reference counting (immediate frees) plus a cyclic GC for reference cycles (generational; incremental with young and old generations since 3.14) | Deterministic destruction for non-cyclic objects. Refcounting under free-threading uses biased reference counting |
| Swift, Objective-C | ARC (automatic reference counting inserted by the compiler) | No tracing GC. Cycles must be broken with weak/unowned |
| Erlang/BEAM | Per-process heaps, each GC'd independently with a generational copying collector; large binaries are refcounted and shared | No global pause: a GC pauses only one tiny process. A great fit for soft real-time |
| Haskell (GHC) | Generational copying; a non-moving collector option for the old generation | Very high allocation rates (immutability) handled by a fast nursery |
| Rust | No GC: ownership and borrowing determine when values are dropped (RAII). Rc/Arc for shared ownership (refcounting, cycles leak unless broken with Weak) |
Deterministic, zero-overhead in the common case. Memory safety without GC, checked at compile time |
| C++ | Manual + RAII; unique_ptr (single owner), shared_ptr (atomic refcount), weak_ptr |
Deterministic. Safety is the programmer's responsibility |
| Zig | Explicit allocators passed as parameters (std.mem.Allocator): general-purpose (DebugAllocator detects leaks and double frees in debug builds), arena, fixed-buffer, page |
Nothing allocates implicitly. Arena allocators per request free everything at once, much like a young generation without tracing |
| C | malloc/free (or custom allocators: jemalloc, mimalloc, arenas) |
Fastest when right; use-after-free, double-free and leaks when wrong |
// Zig: an arena per request: allocate freely, free everything at once (cf. a young generation that's all garbage)
fn handle(req: Request) !Response {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit(); // one free for everything this request allocated
const alloc = arena.allocator();
const body = try std.json.parseFromSliceLeaky(Order, alloc, req.body, .{});
return render(alloc, body);
}
// Rust: values are freed when their owner goes out of scope; no GC, no manual free
fn handle(req: Request) -> Response {
let order: Order = serde_json::from_slice(&req.body).unwrap(); // heap allocations owned by `order`
render(&order)
} // `order` dropped here: memory freed deterministically
// Shared ownership is explicit and counted: let shared = Arc::new(config); let c2 = Arc::clone(&shared);
// Go: in containers, set a soft memory limit so the GC works harder before the OOM-killer strikes
// GOMEMLIMIT=800MiB GOGC=100 ./server (or debug.SetMemoryLimit at run time)
A good mental model: GC trades CPU and memory headroom for programmer productivity and memory safety. Ownership systems (Rust) and explicit allocators (Zig) move that cost to compile time and design time. Arenas show up everywhere: GC nurseries, Zig request arenas, Go's experimental arenas, Postgres memory contexts and C++ std::pmr::monotonic_buffer_resource. "Allocate many short-lived objects together, free them together" is the common insight.
Lab: watching the JIT and the collectors work
Run on JDK 21 on a 2-core machine. Three experiments: how execution speeds up as code is compiled, what polymorphism costs once compiled, and how four garbage collectors handle the same allocation-heavy workload.
Experiment 1: interpreter, C1 and C2
The same loop (two million iterations of shifts, multiplies and XORs) timed eight times in a row, under three settings:
default tiered (C1 then C2): 8.1 2.6 1.2 1.3 0.9 0.9 0.9 0.9 ms
C1 only (-XX:TieredStopAtLevel=1): 5.8 1.6 1.7 1.6 1.6 1.6 1.6 1.6 ms
interpreter only (-Xint): 32.2 32.3 31.4 31.5 31.5 34.1 33.9 33.2 ms
The interpreter never improves: about 32 ms per round, 35× slower than fully compiled code. With the default tiered setup the method moves through tiers: the first round is mostly interpreted (with on-stack replacement swapping in compiled code mid-loop), C1's quick compilation brings it to 1–3 ms, and C2's profile-guided optimisation settles at 0.9 ms. C1 alone warms faster but plateaus about 75% slower. That's the trade tiered compilation makes, and why short-lived processes (CLIs, serverless functions) sometimes run better with C1 only. Add -XX:+PrintCompilation to watch methods move through tiers 0 to 4.
Experiment 2: what a polymorphic call costs after compilation
Summing area() over a million Shapes, where the array holds one, two or four different record types (best of 15 runs):
static double sum(Shape[] xs) { double s = 0; for (Shape x : xs) s += x.area(); return s; }
monomorphic (all Sq): 1.69 ms
bimorphic (Sq or Ci, random): 6.99 ms
megamorphic (4 types, random): 15.42 ms
C2 compiles the call x.area() using the type profile it collected. With one type seen, it inlines Sq.area behind a cheap class check and can then vectorise and optimise the loop: 1.7 ms. With two types it inlines both behind an if/else, which still avoids a call but here the random order makes the CPU's branch predictor guess wrong about half the time. With more than two, the site is megamorphic and HotSpot falls back to a real virtual call through the class's method table on every element, with no inlining: 9× slower than the monomorphic case. This rarely matters in I/O-bound backend code, and you shouldn't contort designs for it, but it explains why tight loops over interfaces with many implementations profile badly, and why sorting data by type, or a sealed-type switch, can speed up hot paths.
Experiment 3: four garbage collectors, one workload
The program keeps about 200 MB of live data (like a cache) and allocates 30 million short-lived arrays of 64–320 bytes, replacing a live megabyte every 65,536 allocations. Each run used a fixed 1 GB heap (-Xms1g -Xmx1g -XX:+AlwaysPreTouch), with pauses read from -Xlog:gc*:
Serial: run 1375 ms | 24 pauses | max 43.92 ms | median 8.59 ms | total paused 242 ms
Parallel: run 1371 ms | 27 pauses | max 20.18 ms | median 7.16 ms | total paused 219 ms
G1: run 1073 ms | 17 pauses | max 7.08 ms | median 3.14 ms | total paused 61 ms
ZGC: run 1019 ms | 30 pauses | max 0.06 ms | median 0.01 ms | total paused ~0 ms
Serial and Parallel stop the application for every collection; Parallel uses both cores to shorten the pause. G1 collects the young generation in short pauses and marks the old generation concurrently, aiming at its 200 ms pause target with lots of room to spare here. ZGC does marking and even moving objects concurrently, pausing only for three tiny synchronisation points per cycle, all under 0.1 ms, at the cost of extra CPU and memory barriers in the running code. On this small heap with 2 cores the concurrent collectors also finished first, because the old-generation copying that Serial and Parallel do in their pauses was done alongside the program instead. On a busy many-core server, Parallel usually wins raw throughput and ZGC wins tail latency: pick by whether your service-level objective is about p99 latency (ZGC, G1) or jobs per hour (Parallel).
One finding from the first attempt, before -XX:+AlwaysPreTouch was added: Serial's first young collection took 1,792 ms, because copying survivors into old-generation memory that had never been touched made the operating system fault in hundreds of megabytes of pages during the pause. In containers and VMs, pre-touching the heap at startup (or a warm-up phase) moves that cost out of the first requests.
Try it yourself
- Run experiment 1 with
-XX:+PrintCompilationand find the line whereLab::workreaches tier 4. Then add-XX:-UseOnStackReplacementand explain round 1's time. - Change experiment 2 to sort the bimorphic array by type before summing. How close to monomorphic does it get, and why?
- Repeat experiment 3 with
-Xmx400m(barely above the live set). Which collectors degrade, and does ZGC report allocation stalls? - Record experiment 3 with
-XX:StartFlightRecording=duration=10s,filename=gc.jfrand open it in JDK Mission Control to see allocation by type and GC phases.
Revision sheet: JVM internals
Key ideas
- Runtimes spectrum: native AOT (C, Rust, Go, Zig), managed VMs with JIT (JVM, .NET, V8), interpreters (CPython); the JVM can also AOT-compile (GraalVM native-image) or cache startup work (Leyden).
- Bytecode: a typed stack machine;
invokestatic/virtual/interface/special/dynamic;invokedynamicunderpins lambdas and string concatenation. - Class loading: load → verify → prepare → resolve → initialise (lazily, on first active use); loader delegation (bootstrap, platform, application); class identity is name plus loader.
- Runtime areas: heap, per-thread stacks, metaspace (class metadata, native memory), code cache.
- Execution: interpreter, tiered C1/C2 (or Graal JIT), on-stack replacement, profile-guided inlining, escape analysis, deoptimisation when assumptions break, safepoints for GC and deopt.
- GC: tracing from roots; generational hypothesis; mark-sweep, mark-compact, copying; card tables and write barriers; Serial, Parallel, G1 (regions, pause target, default), ZGC (concurrent, coloured pointers, generational only since 23), Shenandoah, Epsilon (no-op).
- Elsewhere: Go's concurrent non-moving GC, .NET generations, V8's Orinoco, CPython reference counting, Rust/C++ RAII, Swift ARC.
Numbers to remember
- Lab: interpreter 35× slower than C2 code; C1-only plateau about 75% slower than C2; megamorphic call site 9× slower than monomorphic; GC max pauses on one workload: Serial 44 ms, Parallel 20 ms, G1 7 ms, ZGC 0.06 ms.
- G1 default pause target 200 ms; default max heap 1/4 of physical (or container) memory.
Pitfalls
- Benchmarking without warm-up; judging performance from the first requests after deploy.
- Default heap sizing in containers without checking
MaxRAMPercentage; untouched heap pages faulting during early GCs. - Classloader leaks in app servers and hot reload (metaspace growth).
- Huge numbers of loaded classes and proxies slowing startup.
- Choosing a GC by reputation instead of by the latency or throughput objective and measurement.
Glossary
- JIT: just-in-time compilation during execution.
- OSR: on-stack replacement, switching a running loop to compiled code.
- Deoptimisation: discarding compiled code whose assumptions became false.
- Safepoint: a point where all threads can be paused consistently.
- Megamorphic: a call site that has seen more than two receiver types.
- Write barrier: code run on reference stores so the GC can track changes.