Phase 14 of 20 · Topic 14.5

Diagnosing OutOfMemoryError & JVM Heap Dump Analysis

1Concept

When live objects exceed `-Xmx`, the JVM throws `java.lang.OutOfMemoryError: Java heap space`. Configuring JVM flags `-XX:+HeapDumpOnOutOfMemoryError` and `-XX:HeapDumpPath=/dumps` forces the JVM to capture an exact HPROF heap dump upon failure for post-mortem analysis in Eclipse Memory Analyzer (MAT) or VisualVM.

2Architecture Diagram

[ OutOfMemoryError Occurs ] ---> [ JVM Trigger: -XX:+HeapDumpOnOutOfMemoryError ]
                                              |
                                              v
[ Writes heap_dump.hprof to disk ] ---> [ Eclipse MAT Analysis: Identifies Leak Suspects! ]

3Code Example

Core Java
public class HeapDumpDiagnosticDemo {
    public static void main(String[] args) {
        System.out.println("=== JVM Heap Dump Diagnostic Configuration ===");
        System.out.println("Recommended Production Flags:");
        System.out.println("1. -XX:+HeapDumpOnOutOfMemoryError");
        System.out.println("2. -XX:HeapDumpPath=/var/log/dumps/java_heap.hprof");
        System.out.println("3. -XX:+ExitOnOutOfMemoryError (Ensures container restarts in K8s)");
        System.out.println("\nUse 'jcmd <pid> GC.heap_dump /tmp/dump.hprof' to capture on-demand.");
    }
}

4Expected Output

=== JVM Heap Dump Diagnostic Configuration ===
Recommended Production Flags:
1. -XX:+HeapDumpOnOutOfMemoryError
2. -XX:HeapDumpPath=/var/log/dumps/java_heap.hprof
3. -XX:+ExitOnOutOfMemoryError (Ensures container restarts in K8s)

Use 'jcmd <pid> GC.heap_dump /tmp/dump.hprof' to capture on-demand.

5Key Takeaways

  • Always configure `-XX:+ExitOnOutOfMemoryError` in Kubernetes so pods crash and restart cleanly rather than hanging in zombie state.
  • Use `jcmd <pid> GC.heap_dump /path/dump.hprof` for live production diagnostics without restarting.
  • Dominator tree analysis in Eclipse MAT instantly pinpoints objects holding the largest retained heap size.