Java NotesRohit’s interview study guide
Chapter 10

The JVM: Memory, GC and Performance

What the JVM does with your program while it runs: where objects and stack frames live, how the garbage collector frees memory (and how that compares with V8), why Java code gets faster after warming up, how classes are loaded, how memory still leaks, the tools for looking inside a running JVM, and how to make it start fast and fit in a container. Every example was run with Java 25 (Eclipse Temurin 25.0.5.1) on an 18-core Mac with 64 GB of memory.

Try it yourself. For each example, make an empty folder, save every code box in it under the name in its caption, and type the $ lines of the Terminal box in that folder. Most examples set small limits on purpose (-Xmx32m for a 32 MB heap, -Xss256k for small thread stacks) so that failures happen in a second instead of after eating your memory. A few outputs (GC logs, profiles) contain numbers that change on every run; those Terminal boxes say so, and only the shape of the output will match yours.

8 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#JVM memory: heap, stacks and metaspace

Added

When a JVM runs your program it divides memory into a few areas, and the Java Virtual Machine Specification (chapter 2, "Run-Time Data Areas") names them:

  • The heap, shared by all threads: every object and every array, from new Order() to a String to a byte[]. The garbage collector manages it. Its maximum size is -Xmx; by default it's a quarter of the machine's (or container's) memory.
  • A stack per thread: one frame per method call, holding that call's local variables (primitives directly, objects as references to the heap) and partial results. The stack size is -Xss (2 MB by default on macOS and Linux on ARM, 1 MB on x64, per the java man page). Frames disappear when methods return; no GC needed.
  • Metaspace: class metadata (each loaded class's structure, methods, constant pool), in native memory outside the heap. Before Java 8 this was the "permanent generation" (PermGen), a fixed-size part of the heap you had to size by hand in Java 6 days; since Java 8 it's Metaspace, and its size isn't limited by default.
  • Plus memory the JVM itself uses: JIT-compiled code (the code cache), GC bookkeeping, thread structures, and direct (off-heap) buffers. That's why a JVM process uses more memory than -Xmx.

The mental model for a Node developer: it's the same picture as V8. V8 also has a heap for objects (managed by its GC) and a call stack for frames, and "Maximum call stack size exceeded" is V8's version of StackOverflowError. The differences are in the knobs: V8's old space is capped by --max-old-space-size; the JVM's heap by -Xmx. And the JVM runs many threads, so it has many stacks (one per thread) and one shared heap.

Depth.java
int depth = 0;

void down() {
    depth++;
    down();                 // no base case: recurse until the stack is full
}

void main() {
    try {
        down();
    } catch (StackOverflowError e) {
        IO.println("StackOverflowError, deeper than 10,000 calls: " + (depth > 10_000));
    }
}
Terminal
$ java -Xss256k Depth.java
StackOverflowError, deeper than 10,000 calls: false
$ java -Xss16m Depth.java
StackOverflowError, deeper than 10,000 calls: true
What’s happening
  1. down() calls itself forever. Each call pushes a frame onto the thread's stack, and nothing ever pops one.
  2. With -Xss256k the stack is 256 KB. When it's full, the JVM throws StackOverflowError. When this was written that took about 1,250 calls (the exact depth depends on frame sizes and on whether the JIT had compiled down() yet, so the program prints a stable comparison instead): deeper than 10,000 calls: false.
  3. With -Xss16m the same code went more than 10,000 calls deep before failing: true. (About 340,000 here; the default 2 MB stack gave about 38,000.)
  4. StackOverflowError is an Error, not an Exception (chapter 06). Catching it here is only for the demonstration: by the time it's thrown, the stack is unwound back to main and the frames are gone, so the program can carry on, but real code shouldn't rely on that.
  5. In practice it almost always means unbounded recursion (a missing base case, two methods calling each other, a toString() that prints an object which prints the first one back, a JPA entity graph serialised in a loop). Raising -Xss only hides it; fix the recursion or make it a loop.
AdvancedOutOfMemoryError: the heap is full

When the heap is full and the garbage collector can't free enough, the JVM throws OutOfMemoryError. Keep references to everything you allocate and you'll get there fast with a small heap:

Fill.java
void main() {
    var keep = new ArrayList<byte[]>();
    IO.println("max heap: " + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
    while (true) {
        keep.add(new byte[1024 * 1024]);      // 1 MB that stays reachable
    }
}
Terminal
$ javac Fill.java
$ java -Xmx32m Fill
max heap: 32 MB
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at Fill.main(Fill.java:5)
What’s happening
  1. javac Fill.java compiles the compact source file into Fill.class (running it with java Fill.java works too, but then the stack trace also shows the source launcher's own frames).
  2. -Xmx32m caps the heap at 32 MB, and Runtime.maxMemory() reports it: max heap: 32 MB.
  3. Each loop adds a 1 MB array to a list that main still holds, so nothing is garbage: every array is reachable through keep.
  4. After about 30 arrays the heap is full. The GC runs, finds nothing to free, and the JVM throws java.lang.OutOfMemoryError: Java heap space at the allocation, Fill.main(Fill.java:5). Nothing catches it, so the thread dies and the program exits with status 1.
  5. The detail message tells you which memory ran out. Oracle's troubleshooting guide lists the main ones: Java heap space (objects), Metaspace (class metadata, usually a class loader leak or a huge number of generated classes), GC overhead limit exceeded (the GC runs nearly all the time and frees almost nothing), and Requested array size exceeds VM limit.

#Garbage collection

Added

Java's garbage collector uses the same rule as V8's: an object is kept if it's reachable from a GC root (local variables in active frames of every thread, static fields of loaded classes, JNI references, and a few JVM-internal ones). Everything else is garbage, whatever you meant. Setting a variable to null cuts one path; if a map, a list or a listener still references the object, it stays.

The second idea is also the same as V8's: most objects die young (request objects, temporary strings, iterator objects), so the heap is split into generations. New objects go into the young generation (an "eden" plus survivor spaces), which is collected often and cheaply: the collector copies the few survivors out and treats the rest as free space in one go, so the cost depends on what survives, not on how much garbage there is. Objects that survive several young collections are promoted to the old generation, which is collected less often. V8 calls the same two spaces "new space" (cleaned by a Scavenge) and "old space" (Mark-Compact).

Where Java differs is choice: the JVM ships several collectors, each a different trade-off between throughput (total work done), pause time and memory, and you pick one with a flag. V8 gives you one.

CollectorFlagGood forPauses
G1 (Garbage-First)default since Java 9 (-XX:+UseG1GC)most services: a balance of latency and throughputshort, aiming at -XX:MaxGCPauseMillis (200 ms by default, a soft goal)
ZGC-XX:+UseZGCvery low latency, large heaps (8 MB to 16 TB)"a few milliseconds" whatever the heap size (Oracle's GC guide); generational since Java 21, only mode since 24
Parallel-XX:+UseParallelGCbatch jobs that want maximum throughputlonger stop-the-world pauses, fine if no user is waiting
Serial-XX:+UseSerialGCtiny heaps, one CPUstop-the-world, single-threaded
Shenandoah-XX:+UseShenandoahGClow latency (an OpenJDK collector Oracle's guide doesn't cover); generational mode a product feature in Java 25concurrent, low
Reach.java
import java.lang.ref.WeakReference;

record Session(String user, byte[] data) {}

Map<String, Session> cache = new HashMap<>();

void main() {
    var kept = new Session("rohit", new byte[1_000_000]);
    cache.put("rohit", kept);
    var watchKept = new WeakReference<>(kept);
    kept = null;                                   // the cache still holds it

    var watchTemp = new WeakReference<>(new Session("ana", new byte[1_000_000]));

    System.gc();                                   // ask for a full collection (a hint)

    IO.println("rohit's session still alive: " + (watchKept.get() != null));
    IO.println("ana's session collected: " + (watchTemp.get() == null));

    cache.remove("rohit");
    System.gc();
    IO.println("rohit's session collected after remove: " + (watchKept.get() == null));
}
Terminal
$ java Reach.java
rohit's session still alive: true
ana's session collected: true
rohit's session collected after remove: true
What’s happening
  1. A WeakReference lets you watch an object without keeping it alive: get() returns the object while something else holds it strongly, and null once the GC has collected it. It's Java's WeakRef from JavaScript.
  2. Rohit's session goes into cache, and the local kept is set to null. The object is still reachable: main's frame holds cache (through the implicit instance of this compact source file), the map holds the entry, the entry holds the session.
  3. Ana's session is created and only watched weakly; no strong reference exists anywhere.
  4. System.gc() requests a full collection. It's only a hint (the JVM may ignore it, and -XX:+DisableExplicitGC turns it off), but G1 honours it by default, which makes it usable in a demo. Rohit's session survives (true); Ana's is collected (true).
  5. After cache.remove("rohit") the last strong path is gone, and the next collection frees it: true. Setting kept = null never mattered; removing it from the map did. That's the whole story of Java memory leaks (later in this chapter).
AdvancedReading a GC log

Every collector can log what it does with -Xlog:gc (to the terminal, or to a file with -Xlog:gc:file=<name>) (the JVM's unified logging; the Java 8 era's -XX:+PrintGCDetails still starts, but Java 25 warns that it's deprecated and uses -Xlog:gc* instead). This program creates about 195 MB of short-lived garbage and keeps 2 MB. The numbers in this log change on every run (timings, and how full the heap was when each collection started), so yours won't match; the shape will.

Churn.java
void main() {
    var survivors = new ArrayList<byte[]>();
    long garbage = 0;
    for (int i = 0; i < 200_000; i++) {
        byte[] temp = new byte[1024];          // dies young
        garbage += temp.length;
        if (i % 100 == 0) {
            survivors.add(new byte[1024]);     // lives to the end
        }
    }
    IO.println("allocated " + garbage / (1024 * 1024) + " MB of garbage, kept " + survivors.size() + " KB");
}
Terminal
$ javac Churn.java
$ java -Xlog:gc:file=g1.log -Xmx64m Churn
allocated 195 MB of garbage, kept 2000 KB
$ head -3 g1.log
[0.010s][info][gc] Using G1
[0.068s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 35M->1M(64M) 1.157ms
[0.075s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 30M->1M(64M) 1.453ms
$ java -XX:+UseParallelGC -Xlog:gc:file=parallel.log -Xmx64m Churn
allocated 195 MB of garbage, kept 2000 KB
$ head -2 parallel.log
[0.013s][info][gc] Using Parallel
[0.065s][info][gc] GC(0) Pause Young (Allocation Failure) 17M->1M(61M) 0.976ms
$ java -XX:+UseZGC -Xlog:gc:file=z.log -Xmx64m Churn
allocated 195 MB of garbage, kept 2000 KB
$ head -1 z.log
[0.056s][info][gc] Using The Z Garbage Collector
What’s happening
  1. [0.019s][info][gc] Using G1: each line starts with the time since the JVM started, the level and the log tag. The first line names the collector: G1 is the default here.
  2. GC(0) Pause Young (Normal) (G1 Evacuation Pause) 35M->1M(64M) 1.111ms (the numbers from one run): collection number 0 was a young collection that paused the application; the young regions had filled up, G1 copied ("evacuated") the live objects out, and heap use went from 35 MB to 1 MB of a 64 MB heap, in about a millisecond. 34 MB of garbage cost almost nothing to free, because the cost depends on survivors, not on garbage.
  3. With -XX:+UseParallelGC the line says Pause Young (Allocation Failure): "allocation failure" just means the young generation was full, the normal trigger (V8's GC trace uses the same phrase).
  4. -XX:+UseZGC logs Using The Z Garbage Collector. ZGC's later lines look different (Minor Collection, Major Collection) because it does most of its work while your threads keep running.
  5. -Xlog:gc:file=g1.log sends the log to a file, so the terminal shows only the program's own line, allocated 195 MB of garbage, kept 2000 KB, and head shows the start of each log; the full log has a line per collection. In production you'd also give the file rotation options (see the -Xlog section of the java man page).
AdvancedChoosing and tuning, in practice
  • Start with the default (G1) and measure. Most tuning that people did in the Java 6 days (CMS flags, PermGen sizes, survivor ratios) is gone or unnecessary: PermGen went in Java 8, and the CMS collector is gone too (Java 25 answers -XX:+UseConcMarkSweepGC with "Unrecognized VM option").
  • Set the heap size, not twenty flags: -Xmx (or, in containers, -XX:MaxRAMPercentage, see the last topic). Then look at the GC log or JFR's GC events.
  • Switch to ZGC when pause times matter more than raw throughput (p99 latency targets, large heaps).
  • Big pauses usually mean too little heap or too much garbage. Reducing allocation in hot paths (fewer temporary objects, streaming instead of loading everything) helps every collector.
  • The small-container gotcha: on a machine or container with fewer than 2 CPUs or less than about 1.8 GB of memory, Java 25 picks Serial, not G1 (shown in the last topic). Java 27 (JEP 523) makes G1 the default everywhere.

#JIT compilation and warm-up

Added

The JVM starts by interpreting bytecode (chapter 01): simple, starts instantly, slow. While it interprets, it counts how often each method is called and how often each loop goes round. Hot code is then compiled to machine code by two JIT compilers, a scheme called tiered compilation (on by default):

  • C1 (the "client" compiler) compiles quickly with light optimisation, and adds profiling code that records which branches are taken and which types really arrive.
  • C2 (the "server" compiler) recompiles the hottest methods using that profile: inlining, loop unrolling, escape analysis, and speculative optimisations ("this call always gets an ArrayList"). If a speculation turns out wrong, the JVM deoptimises back to the interpreter and compiles again later.

HotSpot numbers these tiers 0 to 4 (from its source, compilerDefinitions.hpp): 0 is the interpreter, 1 to 3 are C1 (3 is C1 with full profiling, the usual step), 4 is C2.

The mental model for a Node developer: it's V8's pipeline (Ignition interprets, then Sparkplug and Maglev compile quickly, then TurboFan optimises the hot code with type feedback and deoptimises when types change). Both runtimes start slow and get fast, and both punish code whose types keep changing. What Java adds is that the bytecode is already parsed and type-checked, so the JIT works from richer information than raw JavaScript.

Warmup.java
int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

long timeBatch() {
    long start = System.nanoTime();
    long total = 0;
    for (int i = 0; i < 10_000; i++) {
        total += digitSum(i);
    }
    if (total != 180_000) throw new AssertionError(total);   // use the result
    return System.nanoTime() - start;
}

void main() {
    long first = timeBatch();
    long best = Long.MAX_VALUE;
    for (int round = 0; round < 2_000; round++) {
        best = Math.min(best, timeBatch());
    }
    IO.println("first batch at least 5x slower than the best later one: " + (first > 5 * best));
}
Terminal
$ java Warmup.java
first batch at least 5x slower than the best later one: true
What’s happening
  1. timeBatch() calls digitSum 10,000 times and returns how long it took. It checks the total (the digit sums of 0 to 9,999 add up to 180,000) so the JIT can't decide the work is unused and skip it.
  2. First run: the first batch runs mostly in the interpreter. Over the next 2,000 batches digitSum gets compiled by C1, then C2, and the best batch is much faster. When this was written the first batch was 7 to 13 times slower than the best one; the program prints the stable conclusion: true.
  3. Try java -Xint Warmup.java: -Xint turns the JIT off, so everything stays interpreted, the first batch and the best batch cost about the same, and it prints false (and the run takes far longer). That run isn't part of this page's checked output because it's noise-sensitive: while other programs were running, an interrupted first batch made it print true in about one run in four.
  4. This is warm-up: a freshly started JVM is slow for its first seconds or minutes of traffic, then fast. It's why load tests discard the first minutes, why a new instance should get traffic gradually, and why short-lived JVMs (CLI tools, serverless functions) never reach full speed. The last topic shows the fixes.
AdvancedWatching the JIT work

-XX:+PrintCompilation prints a line each time the JIT compiles a method. Filtered to digitSum, it shows the tiers. (sed drops the first two columns, a timestamp and a compile id that change between runs.) The C1 step isn't the same in every run, which is a lesson in itself, so the first box is one real run whose tier numbers may differ from yours (its numbers are compared loosely), and the second box keeps only the tier-4 lines, the part that's the same every time.

Warmup.java
int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

void main() {
    long total = 0;
    for (int round = 0; round < 200; round++) {
        for (int i = 0; i < 10_000; i++) {
            total += digitSum(i);
        }
    }
    IO.println("total: " + total);
}
Terminal
$ javac Warmup.java
$ java -XX:+PrintCompilation Warmup | grep 'Warmup::digitSum' | sed -E 's/^ *[0-9]+ +[0-9]+ //'
      3       Warmup::digitSum (23 bytes)
      4       Warmup::digitSum (23 bytes)
      3       Warmup::digitSum (23 bytes)   made not entrant: not used
%     4       Warmup::digitSum @ 2 (23 bytes)
Terminal
$ java -XX:+PrintCompilation Warmup | grep 'Warmup::digitSum' | sed -E 's/^ *[0-9]+ +[0-9]+ //' | grep -E '^%? +4 '
      4       Warmup::digitSum (23 bytes)
%     4       Warmup::digitSum @ 2 (23 bytes)
What’s happening
  1. The first line is C1 compiling digitSum after it has been called enough times in the interpreter. Usually it's tier 3 (C1 with full profiling). When this page's checker ran several programs at once, it was sometimes tier 2 (C1 with lighter profiling): HotSpot picks tier 2 when the C2 compiler's queue is long, so the same program compiles differently on a busy machine.
  2. The tier 4 line is C2 recompiling it with the profile C1 gathered. From then on calls run the C2 code.
  3. A line with % is an on-stack replacement (OSR) compile: @ 2 means a compiled version of the loop starting at bytecode 2, swapped in while the loop is still running. That's how a long loop inside one call gets faster without waiting for the next call.
  4. The C1 version is then marked "made not entrant" (no new calls may enter it) once C2's version exists. Without the grep, the output lists every method the JVM compiles, including thousands from the JDK itself.
AdvancedWhy micro-benchmarks lie, and JMH

Timing code with System.nanoTime() around a loop, as above, is fine for showing warm-up and useless for comparing two implementations. The JIT may compile one version and not the other yet, inline one into the loop, notice a result is unused and remove the work (dead-code elimination), fold constants, or have a GC land in the middle. JMH (the Java Microbenchmark Harness, from the OpenJDK project) handles all of that: it forks a fresh JVM, runs warm-up iterations before measuring, makes you return results (or feed them to a Blackhole) so nothing is eliminated, and reports an error margin.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>bench</artifactId>
    <version>1.0</version>

    <properties>
        <maven.compiler.release>25</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jmh.version>1.37</jmh.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.openjdk.jmh</groupId>
            <artifactId>jmh-core</artifactId>
            <version>${jmh.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.16.0</version>
                <configuration>
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.openjdk.jmh</groupId>
                            <artifactId>jmh-generator-annprocess</artifactId>
                            <version>${jmh.version}</version>
                        </path>
                    </annotationProcessorPaths>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.6.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals><goal>shade</goal></goals>
                        <configuration>
                            <finalName>benchmarks</finalName>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>org.openjdk.jmh.Main</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
src/main/java/bench/JoinBench.java
package bench;

import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.*;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 3, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 3, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(1)
@State(Scope.Thread)
public class JoinBench {
    int count = 100;

    @Benchmark
    public String plusInLoop() {
        String s = "";
        for (int i = 0; i < count; i++) {
            s += i;                        // a new String every time round
        }
        return s;                          // returned, so the JIT can't drop the work
    }

    @Benchmark
    public String stringBuilder() {
        var sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            sb.append(i);
        }
        return sb.toString();
    }
}
Terminal
$ ./mvnw -q package
$ java -jar target/benchmarks.jar 2>&1 | grep -A 2 '^Benchmark' | tr -s ' '
Benchmark Mode Cnt Score Error Units
JoinBench.plusInLoop avgt 3 2.753 ± 18.224 us/op
JoinBench.stringBuilder avgt 3 0.313 ± 0.588 us/op
What’s happening
  1. The pom.xml is a plain Maven project (not Spring Boot): jmh-core as the dependency, JMH's annotation processor to generate the benchmark harness code at compile time (declared explicitly in annotationProcessorPaths, because Java 25's javac only runs annotation processing when an option configures it; its man page says so under -proc), and the shade plugin to pack everything into one runnable target/benchmarks.jar. -q keeps Maven quiet.
  2. Each @Benchmark method is measured separately. @Fork(1) runs them in a fresh JVM, @Warmup runs 3 half-second iterations to let the JIT finish before @Measurement runs 3 more that count. Real benchmarks use more and longer iterations; these are short to keep the page quick.
  3. Both methods return their result. JMH consumes return values (with a Blackhole), so the JIT can't prove the work is unused and remove it, which is the classic way a hand-written benchmark "measures" nothing.
  4. The output is JMH's summary table (tr -s ' ' squeezes its column padding). The numbers differ on every run and every machine, so here they show as N: Score is the average time per call in microseconds, Error is the 99.9% confidence interval around it. On this Mac += in a loop came out several times slower than StringBuilder for 100 numbers, because every += copies the whole string so far.
  5. Read the Error column before believing a Score: when the error is as large as the difference between two scores, the run doesn't tell them apart. JMH itself prints a warning above the table that its numbers are "just data" to be checked, not conclusions.

#Class loading

Added

A class isn't loaded when the program starts; it's loaded the first time it's needed, by a class loader, and initialised (its static fields set and static {} blocks run) the first time it's actively used: an instance created, a static method called, a non-constant static field read. Initialisation happens exactly once, and the JVM guarantees it's thread-safe, which is why "initialise on first use" holders are a classic lazy-singleton trick.

The built-in loaders form a chain, and each asks its parent first ("parent delegation"), so your code can't replace java.lang.String with its own:

  • Bootstrap loader: built into the JVM, loads the core of the JDK (java.base). Code sees it as null.
  • Platform loader: the rest of the Java SE and JDK modules (java.sql, java.net.http …).
  • Application (system) loader: your classpath or module path. Spring Boot's fat JARs add their own loader on top to read JARs nested inside the JAR (chapter 11).

The Node comparison: require() loads and runs a module the first time it's required and caches it, and that's close to class initialisation. The difference is that Node runs a module's top-level code when it's imported; Java runs a class's static initialiser when the class is first used, and an import line does nothing at run time (chapter 01).

Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("main starts");
        System.out.println("loaders: String=" + String.class.getClassLoader()
                + ", java.sql.Date=" + java.sql.Date.class.getClassLoader().getName()
                + ", Main=" + Main.class.getClassLoader().getName());
        Config unused = null;                       // declaring a variable initialises nothing
        System.out.println("before first use");
        System.out.println("timeout = " + Config.TIMEOUT);
        System.out.println("timeout again = " + Config.TIMEOUT);
        System.out.println("name = " + Config.NAME);
    }
}

class Config {
    static final String NAME = "shop";              // a compile-time constant
    static final int TIMEOUT;
    static {
        System.out.println("Config initialised");
        TIMEOUT = 30;
    }
}
Terminal
$ javac Main.java
$ java Main
main starts
loaders: String=null, java.sql.Date=platform, Main=app
before first use
Config initialised
timeout = 30
timeout again = 30
name = shop
$ java -Xlog:class+load:stdout:none Main | grep -E '^(Main|Config) '
Main source: file:<project>/
Config source: file:<project>/
Config initialised
What’s happening
  1. String's loader prints as null: it's the bootstrap loader inside the JVM. java.sql.Date comes from the platform loader, and Main from the app (application) loader, which reads the classpath (here the current folder).
  2. Config unused = null; mentions the class but doesn't use it, so nothing happens: before first use prints before any sign of Config.
  3. Reading Config.TIMEOUT is the first active use. The JVM initialises Config, which runs its static {} block (Config initialised) and sets TIMEOUT; only then is timeout = 30 printed.
  4. The second read prints just timeout again = 30: initialisation happens once.
  5. Config.NAME is a static final String set to a literal, a compile-time constant. javac copied "shop" into Main itself, so reading it doesn't touch Config at all. (Had it come first, Config would never have been initialised by it.)
  6. -Xlog:class+load logs every class as it's loaded (:stdout:none drops the time stamps). Filtered to the two classes, Main and Config each came from a file: URL, the folder on the classpath, which the page shows as <project>. Without the filter you'd see about 400 JDK classes before Main, most loaded from the JDK's CDS archive ("shared objects file"), which the last topic explains.
AdvancedNoClassDefFoundError after a failed static initialiser

If a static initialiser throws, the class is marked as failed, permanently, for the life of the JVM. The first use gets ExceptionInInitializerError; every later use gets NoClassDefFoundError, which confuses people because the class file is right there.

Prices.java
class PriceTable {
    static final Map<String, Integer> PRICES = load();

    static Map<String, Integer> load() {
        throw new IllegalStateException("prices.csv not found");
    }
}

void main() {
    for (int attempt = 1; attempt <= 2; attempt++) {
        try {
            IO.println(PriceTable.PRICES.get("keyboard"));
        } catch (Throwable e) {
            IO.println("attempt " + attempt + ": " + e.getClass().getName() + ": " + e.getMessage());
            if (e.getCause() != null) IO.println("  cause: " + e.getCause());
        }
    }
}
Terminal
$ java Prices.java
attempt 1: java.lang.ExceptionInInitializerError: null
  cause: java.lang.IllegalStateException: prices.csv not found
attempt 2: java.lang.NoClassDefFoundError: Could not initialize class Prices$PriceTable
  cause: java.lang.ExceptionInInitializerError: Exception java.lang.IllegalStateException: prices.csv not found [in thread "main"]
What’s happening
  1. The first access to PriceTable.PRICES triggers initialisation, and load() throws. The JVM wraps it: attempt 1 gets java.lang.ExceptionInInitializerError (its own message is null), with the real problem as its cause: IllegalStateException: prices.csv not found.
  2. The class is now in an "erroneous" state. Attempt 2 doesn't retry the initialiser: it gets java.lang.NoClassDefFoundError: Could not initialize class Prices$PriceTable straight away. (Prices$PriceTable because a compact source file nests its classes inside a class named after the file.)
  3. On Java 25 the NoClassDefFoundError also has a cause: an ExceptionInInitializerError that records the original exception and the thread it happened in (Exception java.lang.IllegalStateException: prices.csv not found [in thread "main"]), so the trail leads back to the first failure.
  4. In a server log you often see only the NoClassDefFoundErrors (thousands of them) and must scroll back to the first ExceptionInInitializerError to find the real cause. And the general lesson: keep static initialisers trivial; anything that can fail (files, network, config) belongs in normal code, or in a Spring bean that fails at startup.

#Memory leaks in a garbage-collected language

Added

A garbage collector frees objects that are unreachable. It can't free objects you can still reach and will never use again. A Java memory leak is a reference you forgot about, and it's the same in Node: the collector is doing its job perfectly; the program is holding on.

The usual suspects, which Rohit's Node notes list for V8 too:

  • Static collections that only grow: a static Map used as a cache with no eviction, a static List of "recent requests for debugging". Static fields are GC roots, so everything they reference lives for the life of the class (usually the JVM).
  • Listeners and callbacks never removed: you register with a long-lived publisher, the publisher's list keeps you alive. Node's MaxListenersExceededWarning exists for exactly this.
  • ThreadLocals on pooled threads: a pool thread lives for the whole application, so a value set in a ThreadLocal and never remove()d stays referenced until the thread dies. In an app server with redeployments it can also pin a whole class loader (a Metaspace leak).
  • Unbounded caches and queues: a HashMap cache keyed by user input, a newFixedThreadPool whose unbounded queue grows faster than tasks finish (chapter 09).
  • Inner classes and lambdas capturing more than you think: a non-static inner class holds its outer object (chapter 03), so storing one in a long-lived place keeps the outer object too.
  • Resources not closed: streams, connections, and their native buffers; try-with-resources fixes it (chapter 06).

The symptom is a heap whose use after each full GC keeps rising until OutOfMemoryError. The diagnosis is to find which objects there are too many of, and who holds them: a class histogram first, then a heap dump.

Leak.java
record Request(int id, byte[] body) {}

class Handler {
    static final List<Request> recent = new ArrayList<>();   // "for debugging"

    void handle(Request r) {
        recent.add(r);                                       // never removed
    }
}

void main() throws InterruptedException {
    var handler = new Handler();
    for (int i = 0; i < 50_000; i++) {
        handler.handle(new Request(i, new byte[100]));
    }
    IO.println("handled 50000 requests");
    Thread.sleep(Duration.ofMinutes(1));                     // stay up, like a server
}
Terminal
$ java Leak.java & sleep 4; jcmd $! GC.class_histogram | grep -E '^ num|Leak\$Request'; kill $!
handled 50000 requests
 num     #instances         #bytes  class name (module)
   2:         50000        1200000  Leak$Request
What’s happening
  1. The handler keeps every request in a static list "for debugging". After 50,000 requests they're all still reachable from a static field, a GC root, so none can be collected.
  2. java Leak.java & runs it in the background, and after 4 seconds jcmd <pid> GC.class_histogram asks the running JVM for a histogram: for each class, the number of live instances and their total bytes. ($! is the background process's id; in real life jcmd with no arguments lists the JVMs and their pids.)
  3. The histogram first runs a full GC, so it counts only live objects. Leak$Request has exactly 50000 instances, 1200000 bytes (24 bytes each, plus each one's 100-byte array, which is counted under [B, Java's name for byte[]). Requests are supposed to die after they're handled; 50,000 live ones is the leak, in one line.
  4. A histogram tells you what is piling up, not who holds it. For that you take a heap dump (jcmd <pid> GC.heap_dump /tmp/app.hprof) and open it in a tool such as Eclipse MAT or VisualVM, which show the "path to GC roots": here Handler.recent → ArrayList → Object[] → Request. Oracle's troubleshooting guide suggests taking a series of histograms a few minutes apart and watching which counts keep growing.
  5. kill $! stops the program; the grep keeps the header and the line that matters out of a histogram hundreds of lines long.
AdvancedThe fix: bound what you keep

Most leaks are fixed the same way: give the collection a limit or a lifetime. A LinkedHashMap with removeEldestEntry is a bounded LRU cache in a few lines (chapter 07); in a real service you'd use a cache library with size and time limits (Caffeine, chapter 17).

Cache.java
Map<Integer, byte[]> cache;

byte[] render(int productId) {
    return cache.computeIfAbsent(productId, id -> new byte[10_000]);  // a 10 KB "page"
}

void main(String[] args) {
    if (args[0].equals("bounded")) {
        cache = new LinkedHashMap<>(16, 0.75f, true) {
            protected boolean removeEldestEntry(Map.Entry<Integer, byte[]> eldest) {
                return size() > 500;                                   // keep the 500 most recent
            }
        };
    } else {
        cache = new HashMap<>();                                       // keeps everything
    }
    try {
        for (int id = 0; id < 10_000; id++) {
            render(id);
        }
        IO.println("served 10000 products, cache holds " + cache.size());
    } catch (OutOfMemoryError e) {
        cache = null;                     // drop the cache so there's memory to report with
        IO.println("unbounded cache: " + e);
    }
}
Terminal
$ java -Xmx32m Cache.java unbounded
unbounded cache: java.lang.OutOfMemoryError: Java heap space
$ java -Xmx32m Cache.java bounded
served 10000 products, cache holds 500
What’s happening
  1. render caches a 10 KB page per product id. 10,000 different ids would need about 100 MB if every page were kept.
  2. Unbounded (a plain HashMap): every page stays reachable from the map, and after a few thousand pages a 32 MB heap runs out: java.lang.OutOfMemoryError: Java heap space. The program catches it only to report it; first it sets cache = null, because while the full map is still reachable even printing a line can fail for lack of memory (an uncaught OutOfMemoryError here sometimes ended with Java's terse "thrown from the UncaughtExceptionHandler" message instead of a stack trace). Real code shouldn't catch OutOfMemoryError; it should let the process die and restart.
  3. Bounded: a LinkedHashMap in access order (true) that removes its eldest entry once it holds more than 500. Old pages become unreachable as new ones arrive, so at most about 5 MB is live at any time, and the program finishes: cache holds 500.
  4. The leak and the fix differ by one decision: how many is enough? Every cache, queue and buffer in a long-running service needs an answer, in entries, bytes or time.

#Looking inside a running JVM

Added

Node gives you --inspect and Chrome DevTools. The JDK ships its own set of tools in bin/, and the two worth knowing by heart are:

  • jcmd: send a diagnostic command to a running JVM by pid. jcmd alone lists the JVMs; jcmd <pid> help lists the commands. The ones you'll use: Thread.print (thread dump), GC.heap_info, GC.class_histogram, GC.heap_dump <file>, VM.flags, VM.system_properties, VM.native_memory (needs -XX:NativeMemoryTracking=summary at startup), and JFR.start / JFR.dump / JFR.stop. Oracle's troubleshooting guide recommends it over the older jmap, and it covers what jstack and jinfo do too.
  • JDK Flight Recorder (JFR): a low-overhead event recorder built into the JVM, meant to be usable on production systems. It records method samples (where CPU time goes), allocations, GC pauses, lock contention, I/O, exceptions and more into a .jfr file. Start it at launch with -XX:StartFlightRecording, or on a running JVM with jcmd <pid> JFR.start; read the file with the jfr tool (jfr summary, jfr view, jfr print) or open it in JDK Mission Control.

The mental model: jcmd is a remote control, JFR is a flight data recorder. jcmd answers "what is it doing right now?"; JFR answers "what happened over the last few minutes?"

This is the incident workflow: a service is burning CPU, so you start a recording on the live process and ask which methods were hot. The numbers change every run, so they show as N here.

Busy.java
long slowHash(String s) {
    long h = 0;
    for (int round = 0; round < 2_000; round++) {
        for (int i = 0; i < s.length(); i++) {
            h = h * 31 + s.charAt(i) + round;
        }
    }
    return h;
}

void main() {
    IO.println("serving");
    long result = 0;
    for (int calls = 0; ; calls++) {                 // runs until killed, like a server
        result += slowHash("order-" + calls);
        if (result == 42) IO.println("unlikely");
    }
}
Terminal
$ java Busy.java & sleep 3; jcmd $! JFR.start duration=3s filename=live.jfr; sleep 5; kill $!
serving
65369:
Started recording 1. The result will be written to:

<project>/live.jfr
$ jfr view hot-methods live.jfr | awk '/^Busy.slowHash/ {print $1, $NF}'
Busy.slowHash(String) 98.39%
$ jfr summary live.jfr | grep -E ' jdk\.(ExecutionSample|GarbageCollection) ' | awk '{print $1, $2}'
jdk.ExecutionSample 124
jdk.GarbageCollection 0
What’s happening
  1. Busy stands in for a service stuck in a CPU-heavy method. It's started in the background; after 3 seconds, jcmd <pid> JFR.start duration=3s filename=live.jfr starts a 3-second recording on the already running process. No restart, no agent, no code change. jcmd answers with the pid, "Started recording 1" and where the file will be written.
  2. Five seconds later the recording is finished and written, and kill stops the program.
  3. jfr view hot-methods ranks methods by how often JFR's sampler caught them running. Busy.slowHash(String) accounts for nearly all samples (98 to 100% when this was written): the culprit, found in seconds.
  4. jfr summary counts the recorded events by type. jdk.ExecutionSample is the method sampling behind hot-methods (about a hundred samples in 3 seconds); jdk.GarbageCollection is 0 because this program barely allocates. The full summary lists dozens of event types, from class loading to socket reads.
  5. JFR is designed as a low-overhead recorder, which is why teams run services with -XX:StartFlightRecording permanently (with a size or age limit) and dump the last minutes when something goes wrong.
AdvancedHeap dumps on OutOfMemoryError

An OutOfMemoryError in production is gone by the time you look. Set -XX:+HeapDumpOnOutOfMemoryError in advance and the JVM writes the heap to a file at the moment it fails. The file name holds the pid and the sizes change, so those numbers vary here.

Fill.java
void main() {
    var keep = new ArrayList<byte[]>();
    while (true) {
        keep.add(new byte[1024 * 1024]);
    }
}
Terminal
$ javac Fill.java
$ java -Xmx32m -XX:+HeapDumpOnOutOfMemoryError Fill
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid65378.hprof ...
Heap dump file created [19496537 bytes in 0.016 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at Fill.main(Fill.java:4)
$ ls *.hprof | wc -l
       1
What’s happening
  1. The same heap-filling program as at the start of the chapter, with a 32 MB heap.
  2. When the allocation fails, the JVM prints java.lang.OutOfMemoryError: Java heap space, writes the heap to java_pid<pid>.hprof in the current folder ("Dumping heap to … Heap dump file created [… bytes in … secs]"), and then the error is thrown as usual and ends the program with its stack trace. -XX:HeapDumpPath chooses another file or folder.
  3. ls confirms one dump file exists. It's about the size of the live objects (here about 19 MB, under the 32 MB limit), which is why production setups point -XX:HeapDumpPath at a disk with room, and why dumps of a 16 GB heap are a project of their own.
  4. Open the .hprof in Eclipse MAT or VisualVM and look at the "dominator tree" (which objects keep the most memory alive): here one ArrayList holding about 30 arrays of 1 MB.
AdvancedWhat you'd do in an incident
SymptomFirst moves
High CPUJFR (jcmd <pid> JFR.start duration=60s filename=cpu.jfr), then jfr view hot-methods; or a few thread dumps to see which threads are RUNNABLE in the same frame
Hanging, low CPUTwo or three jcmd <pid> Thread.print a few seconds apart: deadlocks, threads waiting on a pool or a slow downstream call (chapter 09)
Memory growing, then OOMGC log or metrics for the old-gen trend, GC.class_histogram twice, then GC.heap_dump and MAT
Long pausesGC log (-Xlog:gc*) or JFR GC events: pause causes, heap too small, humongous allocations
Process memory far above -XmxVM.native_memory summary (with Native Memory Tracking on): thread stacks, metaspace, code cache, direct buffers

In Kubernetes you'd run these with kubectl exec into the container, which needs a JDK (not just a JRE-style runtime) in the image, or use Spring Boot Actuator's threaddump and heapdump endpoints (chapter 16). Neither was run here.

#Startup, containers and native images

Added

Two practical worries come up in every modern Java deployment: how big the JVM thinks its machine is (in a container, it must see the container's limits, not the host's), and how long it takes to start (warm-up and class loading matter for autoscaling and serverless).

Container awareness. On Linux the JVM reads the container's memory and CPU limits by default (-XX:+UseContainerSupport, on by default) and sizes itself from them. So the default heap is a quarter of the container's memory: 512 MB in a 2 GB container, which surprises people who gave the container 2 GB for the app. The usual setting is -XX:MaxRAMPercentage=75, a percentage that follows the container's limit, rather than a hard-coded -Xmx. The JVM also picks its collector and thread counts from what it sees: fewer than 2 CPUs or less than about 1.8 GB means Serial instead of G1 on Java 25.

Startup. A JVM at startup loads and links thousands of classes and interprets code before the JIT kicks in. Three generations of fixes:

  • CDS (Class Data Sharing): a pre-parsed archive of classes, memory-mapped at startup. The JDK ships a default archive for its core classes and uses it automatically (the "sharing" in java -version's output).
  • The AOT cache (Project Leyden): Java 24 (JEP 483) added an ahead-of-time cache of your app's classes, already loaded and linked, created from a training run; Java 25 made it one step with -XX:AOTCacheOutput (JEP 514) and added method profiles so the JIT warms up faster (JEP 515). JEP 483 measured Spring PetClinic starting in 4.486 s without and 2.604 s with the cache on JDK 24, a 42% improvement.
  • GraalVM native image: compile the whole app ahead of time into a native executable. Starts in milliseconds and uses less memory, but it's a different world (below).

Containers can't be run on this Mac, but the JVM has flags that make it believe it has a given number of CPUs and amount of memory, which is enough to see the ergonomics a small container would get:

Terminal
$ java -XX:MaxRAM=2g -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' MaxHeapSize | MaxRAMPercentage '
   size_t MaxHeapSize                              = 536870912                                 {product} {ergonomic}
   double MaxRAMPercentage                         = 25.000000                                 {product} {default}
$ java -XX:MaxRAM=2g -XX:MaxRAMPercentage=75 -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' MaxHeapSize '
   size_t MaxHeapSize                              = 1610612736                                {product} {ergonomic}
$ java -XX:ActiveProcessorCount=1 -XX:MaxRAM=2g -Xlog:gc:stdout:none -version 2>/dev/null
Using Serial
$ java -XX:ActiveProcessorCount=2 -XX:MaxRAM=2g -Xlog:gc:stdout:none -version 2>/dev/null
Using G1
What’s happening
  1. -XX:MaxRAM=2g tells the JVM to size the heap as if it had 2 GB of memory (the java man page: the memory "the JVM may use for the Java heap before applying ergonomics heuristics"), and -XX:+PrintFlagsFinal prints every flag's final value. MaxHeapSize is 536870912 bytes, 512 MB: the default MaxRAMPercentage of 25 per cent of 2 GB, marked {ergonomic} because the JVM chose it.
  2. With -XX:MaxRAMPercentage=75 the same "2 GB container" gets 1610612736 bytes, 1.5 GB of heap, leaving 512 MB for metaspace, thread stacks, the code cache and the OS. That's the common production setting; going near 100% risks the container being killed for exceeding its memory limit, because the JVM uses memory outside the heap.
  3. -XX:ActiveProcessorCount=1 makes the JVM believe it has one CPU. -Xlog:gc:stdout:none prints the GC log without decorations, and its first line names the collector: Using Serial. A Spring Boot service in a 1-CPU pod gets the single-threaded collector unless you say otherwise.
  4. With 2 CPUs the same JVM picks Using G1. (MaxRAM only changes heap sizing; the "server-class" test, two or more processors and at least 1792 MB per Oracle's ergonomics guide, used this Mac's real 64 GB, so CPU count was the deciding factor here. A real 2 GB container limit would count too.) The fix for small pods is either more than one CPU, or an explicit -XX:+UseG1GC. Java 27 (JEP 523) makes G1 the default everywhere.
  5. In a real container you'd check the same things with java -XX:+PrintFlagsFinal -version | grep MaxHeapSize inside the pod, or -Xlog:os+container=trace to see the limits the JVM detected. That wasn't run here (no containers on this Mac); the flags above stand in for it.
AdvancedThe AOT cache (Java 25)

The AOT cache needs a JAR (JEP 483: class paths may contain only JAR files) and the same JDK, OS and class path in the training and production runs.

App.java
import java.net.http.HttpClient;
import java.time.format.DateTimeFormatter;
import java.util.logging.Logger;

public class App {
    public static void main(String[] args) {
        var client = HttpClient.newHttpClient();
        var log = Logger.getLogger("app");
        var fmt = DateTimeFormatter.ISO_LOCAL_DATE;
        var words = java.util.stream.Stream.of("b", "a", "c").sorted().toList();
        System.out.println("ready: " + words + " " + (client != null) + " " + (log != null) + " " + (fmt != null));
    }
}
Terminal
$ javac -d classes App.java
$ jar --create --file app.jar --main-class App -C classes .
$ java -XX:AOTCacheOutput=app.aot -jar app.jar 2>&1 | grep -E 'ready|AOTCache creation'
ready: [a, b, c] true true true
AOTCache creation is complete: app.aot 20905984 bytes
Terminal
$ java -XX:AOTCache=app.aot -Xlog:class+load:stdout:none -jar app.jar | grep -E '^(App|java.net.http.HttpClient) '
java.net.http.HttpClient source: shared objects file
App source: shared objects file
$ java -Xlog:class+load:stdout:none -jar app.jar | grep -E '^(App|java.net.http.HttpClient) '
App source: file:<project>/app.jar
java.net.http.HttpClient source: jrt:/java.net.http
What’s happening
  1. App touches a few JDK areas a real service would (the HTTP client, logging, java.time, streams). It's compiled and packed into app.jar.
  2. Training run: -XX:AOTCacheOutput=app.aot runs the app normally (it prints ready: …), records which classes it loaded and linked, then starts a second JVM that writes the cache: AOTCache creation is complete: app.aot … bytes (about 20 MB here; the size depends on the app and JDK, so it shows as N). The full output also has some harmless warnings about classes it skipped, which grep hides.
  3. Production run with -XX:AOTCache=app.aot: the class-loading log shows App and java.net.http.HttpClient coming from the shared objects file, the cache, already loaded and linked.
  4. Without the cache, App comes from the JAR (file:<project>/app.jar) and HttpClient from the JDK's module image (jrt:/java.net.http), parsed and linked at startup. The JDK's default CDS archive covers only common core classes; the AOT cache adds your app's classes and the JDK classes your app really uses.
  5. For this tiny app the time saved is small and not worth quoting; it pays off for apps that load thousands of classes at startup, like Spring Boot services (JEP 483's PetClinic figure above). Spring Boot 4.2's reference docs have an "AOT Cache" page: it supports the AOT cache on Java 25+ (CDS before that) and recommends extracting the JAR first (java -Djarmode=tools -jar my-app.jar extract --destination application), training with java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar my-app.jar (the app starts its context and exits), then running with -XX:AOTCache=app.aot. That Spring flow wasn't run for this page.
AdvancedGraalVM native images

A native image is your application compiled ahead of time, with GraalVM's native-image tool, into a platform-specific executable that doesn't need a JVM. Spring Boot supports it (GraalVM 25 or later for Boot 4; ./mvnw -Pnative native:compile, or spring-boot:build-image with the native profile for a container image). The Spring Boot docs describe the trade-off plainly:

  • Gains: "a smaller memory footprint and with much faster startup times", which suits scale-to-zero and function-as-a-service platforms and small containers.
  • Costs: static analysis from main at build time, so code that isn't reachable is removed; reflection, resources, serialisation and dynamic proxies must be declared with hints; the classpath is fixed at build time; and Spring assumes a closed world, so beans can't change at run time (@Profile has limitations, and @ConditionalOnProperty-style switches that decide which beans exist aren't supported). Builds take minutes and lots of memory, and you lose the JIT's profile-guided peak performance unless you use GraalVM's own profile-guided optimisation.

Native images weren't built for this page (GraalVM isn't installed here). The honest summary for an interview: the AOT cache keeps the normal JVM and gets a good part of the startup win with no code changes; native images get the biggest startup and memory win at the cost of build complexity and dynamic features. For a long-running service on Kubernetes, the regular JVM (with the AOT cache and a sensible MaxRAMPercentage) is usually the simplest good answer.

#Your turn: the JVM

Added
Your turn: the heap a 4 GB container gets

Without a container, find out how big the default heap is for a JVM limited to 4 GB of memory, and how big it is with -XX:MaxRAMPercentage=75.

Show answer
Terminal
$ java -XX:MaxRAM=4g -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' MaxHeapSize '
   size_t MaxHeapSize                              = 1073741824                                {product} {ergonomic}
$ java -XX:MaxRAM=4g -XX:MaxRAMPercentage=75 -XX:+PrintFlagsFinal -version 2>/dev/null | grep -E ' MaxHeapSize '
   size_t MaxHeapSize                              = 3221225472                                {product} {ergonomic}
What’s happening
  1. -XX:MaxRAM=4g makes the JVM size its heap as if it had 4 GB, like a container limit would.
  2. The default is 25%: 1073741824 bytes, exactly 1 GB.
  3. With MaxRAMPercentage=75 it's 3221225472 bytes, 3 GB, leaving 1 GB for everything outside the heap.
Your turn: fix the leaking listener registry

This EventBus keeps every listener that subscribes, and each request subscribes a new listener holding 10 KB. Run it with -Xmx32m and it dies after a few thousand requests. Change handleRequest so each request unsubscribes its listener when it's done, and show that 10,000 requests now finish with no listeners left.

Show answer
Bus.java
class EventBus {
    private final List<Consumer<String>> listeners = new ArrayList<>();

    void subscribe(Consumer<String> l) { listeners.add(l); }
    void unsubscribe(Consumer<String> l) { listeners.remove(l); }
    void publish(String event) { listeners.forEach(l -> l.accept(event)); }
    int count() { return listeners.size(); }
}

EventBus bus = new EventBus();

void handleRequest(int id) {
    byte[] state = new byte[10_000];               // per-request data the listener uses
    Consumer<String> listener = e -> state[0]++;
    bus.subscribe(listener);
    try {
        bus.publish("request " + id);
    } finally {
        bus.unsubscribe(listener);                 // the fix: always unsubscribe
    }
}

void main() {
    for (int id = 0; id < 10_000; id++) {
        handleRequest(id);
    }
    IO.println("handled 10000 requests, listeners left: " + bus.count());
}
Terminal
$ java -Xmx32m Bus.java
handled 10000 requests, listeners left: 0
What’s happening
  1. The lambda captures state, so as long as the bus holds the listener, it also holds the request's 10 KB array. Without the unsubscribe, 10,000 requests would keep about 100 MB reachable and a 32 MB heap would run out.
  2. unsubscribe in a finally removes the listener even if publish throws. List.remove finds it by equals, which for a lambda is identity: the same object that was added.
  3. After each request the listener and its array are unreachable and collectable, so the program finishes: listeners left: 0.
  4. The Node version of this bug is an emitter.on(...) without emitter.off(...), and the same fix applies. In Java, try-with-resources with a subscription object that unsubscribes in close() makes it impossible to forget.
Your turn: which collector does a 1-CPU pod get?

A service runs in a pod with 1 CPU and 1 GB of memory. Show which collector Java 25 picks there, and make it use G1 instead.

Show answer
Terminal
$ java -XX:ActiveProcessorCount=1 -XX:MaxRAM=1g -Xlog:gc:stdout:none -version 2>/dev/null
Using Serial
$ java -XX:ActiveProcessorCount=1 -XX:MaxRAM=1g -XX:+UseG1GC -Xlog:gc:stdout:none -version 2>/dev/null
Using G1
What’s happening
  1. -XX:ActiveProcessorCount=1 and -XX:MaxRAM=1g stand in for the pod's limits, and -Xlog:gc:stdout:none prints the collector without decorations.
  2. With one CPU the machine isn't "server-class" to the JVM, so it picks Using Serial.
  3. An explicit -XX:+UseG1GC always wins over ergonomics: Using G1. (Giving the pod 2 CPUs would also do it, as long as it reports at least 1792 MB of memory; and from Java 27 G1 is the default regardless.)

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.