Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Inside the JVM

    Tuning and Diagnosis

    -Xms<size> initial heap size e.g. -Xms2g

    Chapter 10 of 107 min readOften asked in interviews

    10.1 Heap sizing flags#

    Output
      -Xms<size>                   initial heap size           e.g. -Xms2g
      -Xmx<size>                   MAXIMUM heap size           e.g. -Xmx2g
      -Xss<size>                   stack size per thread       e.g. -Xss1m
      -XX:MaxMetaspaceSize=<size>  cap metaspace
      -XX:MaxRAMPercentage=75      heap as a % of the container/machine memory (preferred in containers)
      -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps     write a heap dump when OOM happens
      -Xlog:gc*:file=gc.log        GC logging (Java 9+ unified logging)

    Defaults: without flags, the maximum heap is ¼ of physical memory and the initial heap 1⁄64. On this 16 GB Mac: -XX:MaxHeapSize=4294967296 (4 GB) and -XX:InitialHeapSize=268435456 (256 MB) — exactly ¼ and 1⁄64.

    Servers often set -Xms = -Xmx, so the heap never has to grow or shrink (predictable; the memory is claimed up front).

    The container trap#

    Inside Docker/Kubernetes (DevOps (coming soon)), the container has a memory limit, and exceeding it gets the process OOM-killed by the kernel — exit code 137 (Operating Systems Ch 5, 12) — with no Java error message at all. And the JVM uses memory beyond the heap: metaspace, thread stacks (each thread ~1 MB), the code cache, GC data structures, direct buffers.

      container limit 1 GB
      ┌──────────────────────────────────────────────────────────┐
      │ heap (-Xmx)  │ metaspace │ thread stacks │ code cache │ GC │ ...  → all must fit, or: OOMKilled (137)
      └──────────────────────────────────────────────────────────┘

    Modern JVMs (Java 10+) read the container limit and size the default heap from it. Set -XX:MaxRAMPercentage=75 (leaving ~25% for everything else) rather than a hard -Xmx that someone forgets to change when the limit changes.

    Two different "out of memory" deaths — know which one you have:

    • java.lang.OutOfMemoryError: Java heap space in the logs → the heap is full (live data too big, or a leak). The JVM is still running and can write a heap dump.

    • Container status OOMKilled, exit code 137, no Java error → the whole process exceeded the container limit (heap too large for the limit, too many threads, native memory). The kernel killed it.

    10.2 The diagnostic tools#

    ToolWhat it does
    jcmd <pid> helpthe Swiss-army knife — most tasks below are jcmd commands
    jcmd <pid> GC.heap_infoheap and region usage now
    jstat -gc <pid> 1000GC statistics every second: generation sizes, number and total time of GCs
    jcmd <pid> GC.heap_dump /tmp/heap.hprof (or jmap -dump)a heap dump: a snapshot of every object — open it in Eclipse MAT or VisualVM
    jstack <pid> / jcmd <pid> Thread.printa thread dump: every thread's stack — for deadlocks and stuck threads (Concurrency Ch 6)
    Java Flight Recorder (JFR): jcmd <pid> JFR.start duration=60s filename=rec.jfrlow-overhead recording of allocation, GC, locks, CPU hot spots — safe in production; view in JDK Mission Control
    GC logs (-Xlog:gc*)every pause with its cause and duration (Ch 6)

    10.3 Solving Part 0#

    Problem 1 — 800 ms spikes every few minutes. Turn on GC logs. If the spikes line up with long pauses — especially Pause Full — the collector is the cause. Typical reasons: the old generation filling (premature promotion or a slow leak), humongous allocations in G1, or a heap too small for the live data. Fixes, in order: reduce allocation and object lifetimes, size the heap properly, then consider ZGC for sub-millisecond pauses.

    Problem 2 — memory never drops, then OOM. The textbook leak hunt:

    Output
      1. Confirm: after each full GC, is the heap's "after" number rising over hours?   (GC logs / jstat)
      2. Capture: a heap dump (automatically with -XX:+HeapDumpOnOutOfMemoryError, or jcmd GC.heap_dump)
      3. Analyse: in Eclipse MAT, open the "dominator tree" / "leak suspects" report — which objects retain the most memory?
      4. Trace: follow the "path to GC roots" for those objects — WHY are they still reachable? (Ch 5)
      5. Typical answers: a static Map used as a cache with no eviction; listeners never removed; ThreadLocals in pool threads;
         an ever-growing queue with no consumer; mutable HashMap keys that can't be removed.
      6. Fix: bounded caches with eviction (LRU — 07_java_collections_internals.md Ch 5, or a library like Caffeine),
         remove listeners, clear ThreadLocals in finally, bound queues.

    Problem 3 — slow for a minute after deploy. JIT warm-up (Ch 4) — plus class loading and connection pools starting cold. Warm up before receiving traffic (readiness checks — Kubernetes Fundamentals (coming soon)), roll out instances gradually, consider CDS.

    Check yourself

    4 questions
    1

    What are the default max and initial heap sizes?

    Show answer

    Max = ¼ of physical (or container) memory; initial = 1⁄64.

    2

    A container is OOMKilled with exit 137 but the Java logs show no OutOfMemoryError. What's happening, and what do you set?

    Show answer

    The whole JVM process exceeded the container limit (heap + non-heap memory), and the kernel killed it. Size the heap as a percentage — -XX:MaxRAMPercentage=75 — leaving room for metaspace, thread stacks and native memory (and check thread counts).

    3

    Walk through finding a memory leak from a heap dump.

    Show answer

    Confirm the post-GC heap keeps growing; take a heap dump; find the biggest retained objects (dominator tree); follow their paths to GC roots to see what holds them; fix that reference (e.g. bound the cache).

    4

    Which tool would you use for: a deadlock; which code allocates most; GC pause times over time?

    Show answer

    jstack/jcmd Thread.print; Java Flight Recorder (allocation profiling); GC logs (-Xlog:gc*) or jstat.