Hmm, the user is asking for a memory profiling regimen for JVM services using async-profiler, flamegraphs, and leak hunts. This is a detailed operational question, likely from a DevOps or performance engineer dealing with production systems. They probably want a practical, actionable plan—not just theory.
The query mentions three key tools: async-profiler (for allocation sampling), flamegraphs (visualization), and leak hunts (targeted investigation). So the regimen should integrate these into a workflow, not just list tools. The user might be struggling with intermittent memory issues or OOMs in production, needing a systematic way to catch them.
I should structure this as a phased approach: proactive (baseline), reactive (OOM response), and deep-dive (leaks). Emphasize async-profiler’s low overhead since production use is implied. Flamegraphs need explanation—how to interpret them for memory (alloc stacks vs. heap dumps). Leak hunts should tie to common patterns (e.g., caches, threadlocals).
Also, must warn about pitfalls: async-profiler’s allocation sampling vs. heap dump differences, flamegraph misinterpretation, and the “heap dump vs. live objects” trap. The user might not know that flamegraphs show allocation rates, not retained sizes.
Finally, add automation tips (k8s sidecars, alerts) since they’re likely running in containers. Avoid academic fluff—focus on “here’s what to run, when, and how to read the output.” Maybe include a cheat-sheet table for quick reference.
Excellent question. This is a production-grade, multi-layered memory profiling strategy for JVM services, moving from broad observability to surgical diagnosis. The key is integrating tools for different situations: continuous low-overhead monitoring vs. deep-dive forensics.
Here is a comprehensive regimen designed for real-world, containerized JVM services (e.g., Spring Boot, Micronaut, Quarkus).
Core Philosophy & Tool Roles
async-profiler: The workhorse. Ultra-low overhead (~1-5%), uses perf_events (Linux). Ideal for continuous production profiling of allocation rates (alloc event) and object lifetimes (live allocation profiling). Does not require a full heap dump.
- Flame Graphs (via
async-profiler or jfr): The visualization layer. They transform stack traces into an intuitive "mountain" view, showing which code paths allocate the most memory (width = allocation rate/bytes).
- "Leak Hunts": The targeted investigation phase. Uses heap dumps (
jmap, jcmd, jfr object allocation events) and analysis tools (Eclipse MAT, JProfiler, YourKit) to find retained heap and GC root paths for suspected leaked object types.
Phase 1: Proactive Baseline & Continuous Monitoring (The日常 Regimen)
Goal: Establish "normal" and detect deviations early, with minimal overhead.
| Activity | Tool & Command | Frequency / Trigger | Output & Action |
|---|
| 1. Allocation Rate Profiling | async-profiler -e alloc -d 60s -f /tmp/alloc.svg ` | Continuously in non-prod. Every 5-15 min in prod via sidecar/cron job. | Flame Graph (alloc.svg). Look for: • Sudden spikes in width of specific stacks (e.g., ArrayList.grow()). • New, unexpected allocation sources. Compare to baseline. |
| 2. Garbage Collection Logs | JVM flags: -Xlog:gc*:file=/tmp/gc.log:time,uptime,level,tags | Always on. | Analyze with gcviewer/gceasy. Watch: • Young Gen Allocation Rate (before GC). • Promotion Rate to Old Gen. • Old Gen occupancy trend (is it creeping up?). |
| 3. Key JVM Metrics Export | Micrometer, Prometheus JMX Exporter | Scrape every 15-60s. | Dashboards (Grafana) for: • jvm.memory.used.heap / max • jvm.gc.live.data.size (Old Gen after Full GC) • jvm.memory.pool.used (each pool) • Allocation Rate (jvm.gc.memory.allocated.rate). |
| 4. Baseline Heap Dump (Optional) | jcmd <pid> GC.heap_dump /tmp/baseline.hprof | After stable period, in staging. | Store as "golden" reference. Use MAT to know expected large object types (e.g., ConcurrentHashMap$Node, char[] for string data). |
Integration Pattern:
- K8s/Containers: Run
async-profiler as a sidecar container or via kubectl exec with nsenter (to access host pid/net namespaces). Use profiler.sh from the async-profiler repo.
- Alerting: Set alerts on: Old Gen usage > 75% and trending up over 1h, Allocation Rate spike > 2x baseline.
Phase 2: Reactive Investigation (When You See Symptoms)
Trigger: Old Gen usage high/creeping, frequent Full GCs, OutOfMemoryError (imminent or thrown), or alert from Phase 1.
| Step | Tool & Command | Purpose & Interpretation |
|---|
| 1. Immediate Allocation Snapshot | async-profiler -e alloc -d 30s -f /tmp/alloc_panic.svg ` | First 30s after symptom. Flame graph shows what is allocating right now at high rate. This often points directly to the leak culprit (e.g., a HTTP client connection pool not closing). |
| 2. Live Object Profiling | async-profiler -e live -d 60s -f /tmp/live.svg ` | Shows objects that survive to the current moment. Width = total bytes of live objects on that stack. More valuable than alloc for leaks. Look for stacks with wide bars representing many long-lived objects. |
| 3. On-Heap Analysis: Heap Dump | jcmd <pid> GC.heap_dump /tmp/heap_panic.hprof OR async-profiler -e heapdump -d 60 ` (live objects only) | The canonical source for "what is in heap now?". async-profiler's -e heapdump is faster but captures only reachable objects (similar to jcmd with -live). |
| 4. Deep Dive with Analysis Tool | Eclipse MAT (open-source, powerful) JProfiler/YourKit (commercial, UI better) | a. Histogram: Sort by Shallow Heap. Find unexpected large counts of a class (e.g., 50k char[]). b. Dominator Tree: Find objects with largest retained heap. The top entry is often the leak owner. c. Path to GC Roots: (Exclude weak/soft refs) for a suspicious object. This is the "leak hunt." Find the static field, thread-local, or cache holding it. |
| 5. Correlate with Flame Graph | Compare live.svg to MAT findings. | Does the stack in the flame graph () match the from MAT? This confirms the allocation site. |
Phase 3: Advanced & Contextual Profiling
| Scenario | Tool & Technique | Why & How |
|---|
| Intermittent/Long-Lived Leaks | Java Flight Recorder (JFR) with allocation stack traces. -XX:StartFlightRecording=duration=1h,settings=profile,filename=/tmp/recording.jfr | JFR continuously records allocation events with stack traces with very low overhead (~1%). You can query later: jfr tool or JDK Mission Control to see "Top allocated classes over last 10 min." Excellent for finding leaks that take hours to manifest. |
| Off-Heap / Native Memory | async-profiler -e malloc,mem -f /tmp/mem.svg <br>pmap -x ` | malloc/mem events show native allocations (Direct Buffers, JNI code, JVM internal). mem.svg flame graph shows native call stacks. pmap shows total RSS and mapping breakdown. |
| Thread Local / ClassLoader Leaks | Heap Dump + MAT Analysis focused on: • java.lang.Thread objects & their threadLocals map.• java.lang.ClassLoader instances and their loaded classes. | Use MAT's "Thread Overview" and "Class Loader Explorer" plugins. Look for: • Threads that never die holding large ThreadLocals.• Custom ClassLoaders (e.g., from app servers, OSGi) retained by static fields. |
| Metaspace Leaks | JVM flag: -XX:NativeMemoryTracking=detail jcmd <pid> VM.native_memory detail | Check class (shared) and class (private) growth. Correlate with number of loaded classes from heap dump. |
Practical "Leak Hunt" Workflow (Synthesized)
- Detect: Old Gen trending up, Full GC frequency increasing,
jstat -gc <pid> shows OGCMX nearing OGCT.
- Capture Baseline: Get
alloc and live flame graphs during a "good" period for comparison.
- Capture Panic: Get
live flame graph during/just after high memory usage. Identify the widest, persistent stacks in the live graph. Note the top frames (e.g., com.foo.BufferCache.getBuffer()).
- Get Heap Dump: Use
async-profiler -e heapdump (for quick, live-only) or jcmd GC.heap_dump. Prefer -live to focus on reachable objects.
- Analyze in MAT:
- Run "Leak Suspects Report" (quick first pass).
- Open "Dominator Tree". Sort by Retained Heap. Find the largest objects you don't expect to be that big (e.g., a
byte[] that should be small).
- Right-click suspicious object -> "Path To GC Roots" (exclude weak/soft refs). Trace this path upward.
- The GC root is often: a
static field in a long-lived class, a field in a ThreadLocal, or an entry in a global cache (like a Guava Cache or ConcurrentHashMap).
- Correlate & Conclude: Does the GC root's class/field and the allocation stack from the
live flame graph tell a consistent story? Example: Flame graph shows BufferCache.getBuffer() -> MAT shows BufferCache.instance.bigBufferMap as GC root for a byte[10MB]. LEAK CONFIRMED.
- Validate: (Optional) Use a debugger or add logging to the suspect code path to confirm objects are not being released/cleared.
Cheat Sheet: Commands & Quick Actions
| Situation | Command (run as java user or with sudo) | Key Output |
|---|
| Start 60s alloc profile | async-profiler profiler.sh -e alloc -d 60 -f alloc.svg <pid> | alloc.svg - What's allocating now? |
| Start 60s live profile | async-profiler profiler.sh -e live -d 60 -f live.svg <pid> | live.svg - What's surviving? (CRITICAL FOR LEAKS) |
| Heap dump (all objects) | jcmd <pid> GC.heap_dump heap.hprof | heap.hprof - Full heap state. |
| Heap dump (live only) | jcmd <pid> GC.heap_dump -live live.hprof | live.hprof - Only reachable objects. |
| Native memory summary | jcmd <pid> VM.native_memory summary | stdout - Off-heap breakdown. |
| JFR start (1h, profile) | jcmd <pid> JFR.start name=rec duration=1h settings=profile filename=recording.jfr | recording.jfr - Continuous allocation history. |
| Quick "is it metaspace?" | jcmd <pid> VM.metaspace | used, capacity, committed for class space. |
Critical Pitfalls & Best Practices
alloc vs. live: alloc shows allocation rate. A fast, short-lived object can dominate alloc but cause no leak. live is the primary leak-detection flame graph.
- Flame Graph Misinterpretation: Width = bytes/objects on that stack, NOT retained heap. A wide bar at
ArrayList.add() means many objects were added via that call, but the owner of the ArrayList is higher in the stack or in the GC root path.
- Heap Dump Overhead: Taking a heap dump of a large heap (10GB+) can stop the world for minutes. Use
async-profiler -e heapdump (uses jcmd under the hood but can be more controlled) or schedule during low traffic. Never take a heap dump on a process already dying from OOM; it may fail.
- Compare, Don't Just Look: Always compare
live graphs from "good" vs. "bad" states. The difference is your leak.
- Know Your Libraries: Common leak sources:
- Caches (
Caffeine, Guava, Ehcache) without size/time limits.
- ThreadLocals in thread pools (e.g., from frameworks, logging MDC).
- ClassLoader leaks in hot-deploy environments (Tomcat, OSGi).
- Unclosed resources (
InputStream, ResultSet, Session).
- Collections growing unbounded (e.g., event queues, in-memory stores).
- Automate Profiler Collection: Wrap async-profiler in a script that:
- Auto-detects PID (from JVM name or port).
- Adds timestamps to filenames.
- Archives old profiles (e.g., keep last 10).
- Can be triggered by an alert webhook.
Summary: The Integrated Regimen
- Always On: GC logs, JVM metrics (Prometheus),
async-profiler allocation sampling (light, rolling) for baselines.
- On Alert (High Old Gen): Immediately grab
live flame graph and live heap dump. This is your primary incident response.
- Deep Dive: Analyze heap dump with MAT Dominator Tree & Path to GC Roots. Correlate with
live flame graph to pinpoint allocation site.
- For Mysterious/Slow Leaks: Run a long-duration JFR recording with allocation stack traces, then query "top allocated classes" in a time window before the symptom.
- Remember the Stack: The leak is almost always a path:
Static Field / ThreadLocal / Cache Entry -> Leaky Container (e.g., ArrayList) -> Leaked Object. Your job is to trace this path using the tools in combination.
This regimen shifts you from reactive "heap dump after OOM" to proactive detection and fast, data-driven root cause analysis, minimizing production impact.