1. Understand the Goal: The user wants a "memory profiling regimen" for JVM services. This isn't just a one-off command; it's a process or workflow. The key tools mentioned are async-profiler, flamegraphs, and "leak hunts". The target is JVM (Java/Kotlin/Scala).
Deconstruct the Components:
Memory Profiling: This implies looking at allocation rates, heap usage, garbage collection (GC) behavior, and identifying memory leaks.
Async-profiler: The industry standard for low-overhead profiling. It supports CPU, ALLOC, and LOCK events. For memory, alloc is the crucial mode.
Flamegraphs: The visualization tool. Differentiates between CPU flames, Allocation flames, and "malloc" flames.
Leak Hunts: This refers to identifying objects that are retained longer than necessary or not collected at all. async-profiler has specific capabilities here (seeing where objects were allocated), but distinguishing a leak often requires comparing heap dumps or using specific tools like jcmd or VisualVM/YourKit, though async-profiler can help find the source of the allocation.
Structure the "Regimen": A regimen implies a lifecycle. I should structure this by phases:
Phase 1: Preparation & Baseline (The Setup).
Phase 2: Continuous Low-Overhead Monitoring (The Routine).
Phase 3: Deep Dive/Investigation (The Diagnosis).
Phase 4: Automation/Integration (The CI/CD aspect).
Drafting the Content - Section by Section:
Introduction: Briefly state the philosophy (low overhead, sampling vs. tracing).
Self-Correction:async-profiler 2.x/3.x changed some flags. Need to be specific about the alloc event.
Phase 2: The Routine - Allocation Profiling (Flamegraphs)
Concept: High allocation rate → GC pressure → Latency spikes.
Action: Run profiler.sh -e alloc.
Visualization: Generate the flamegraph (SVG).
Interpretation: Look for "plateaus" and "towers". Taller = more allocations. Wider = frequent allocations in that code path.
Phase 3: The Leak Hunt (The hard part)
Clarification: Async-profiler tells you where objects were created, not necessarily why they are still alive (that's usually a heap dump). However, async-profiler can do live object profiling now (since v2.7+). This is a crucial distinction. It can track object creation and retention if configured right, or simply track allocation intensity.
Strategy:
Allocation Sampling: Identify hot paths creating short-lived or long-lived objects.
Live Object Profiling: (The specific live feature in async-profiler is extremely powerful for leaks). It samples allocation and checks if the object is still alive after a set interval.
Heap Dumps (The Classic):jcmd GC.heap_dump. Compare dominator trees.
Phase 4: Integrating into the Service Lifecycle (Automation)
How to make this a regimen?
Start profiling on startup? (Dangerous for prod unless carefully tuned).
On-demand profiling via HTTP endpoint (using the async-profiler java API). This is the modern way.
Arthas? Good mention, but maybe keep it focused on the requested tools.
Specific Techniques/Tricks:
--live option: This is the secret sauce for leaks with async-profiler.
--live vs standard alloc.
JDK internals: String deduplication, GC logs.
Refining the "Leak Hunt" methodology with Async-profiler:
Standard approach: High allocation rate doesn't equal leak.
Async-profiler approach: Use -e alloc to find hotspots. Use the live option (introduced relatively recently) to find objects that were allocated and survived a specific duration. This bridges the gap between allocation profiling and heap analysis.
Structuring the Output:
Use a hierarchical structure (Philosophy → Tools → Workflow → Analysis).
Include concrete command examples.
Include code snippets for programmatic triggering (essential for services).
Leak command:./profiler.sh -d 60 -e alloc --live -f live.html <pid> (Need to double check exact syntax for live. It's usually --live or inherent in specific modes. Actually, async-profiler uses --live to filter allocation events to only those objects that survived the GC during the profiling session. This is the "Leak Hunter" feature).
C/C++ level: Mention malloc profiling if using JNI, but focus on Java heap.
Final Polish: Add a section on "Sanity Checks" (GC Logs) and "Common Pitfalls" (TLABs, biased locking - though biased locking is gone in newer JDKs).
(Self-Correction during drafting): I initially thought about suggesting MAT (Memory Analyzer Tool) for leaks. While valid, the prompt asks for a regimen integrating async-profiler. I should focus heavily on how async-profiler solves the leak problem (via the live flag and allocation context) rather than just saying "go dump the heap". I will mention heap dumps as a secondary verification step.
Final Output Generation: (This aligns with the detailed response provided previously.)
Designing a memory profiling regimen for JVM services requires a shift in mindset from "debugging crashes" to "continuous physiological monitoring." We need to measure Allocation Rate (pressure), Live Set (footprint), and Leak Suspects (retention).
Here is a comprehensive regimen integrating async-profiler, flame graphs, and leak hunting, structured by lifecycle phase.
1. The Tooling Setup
Standard APMs (DataDog, New Relic) are great for high-level metrics but often lack the granular detail required for deep memory analysis. This regimen relies on direct access to the JVM.
Prerequisites:
JDK Version: JDK 11+ (for modern JFR support), though AP works on JDK 8.
Async-profiler (AP): Version 2.8+ (crucial for the --live feature).
Scripting: A wrapper script to automate AP execution on the server.
2. Phase I: The Baseline (Startup & Steady State)
Before hunting for leaks, you must understand the "breathing rate" of your application.
Objective: Establish the baseline allocation rate and GC behavior.
The Command:
bash
# Record allocation for 60 seconds
./profiler.sh -d 60 -e alloc -f baseline_alloc.html <pid>
Analysis (The Flame Graph):
Look for: "Plateaus" and "Towers".
Interpretation: In an allocation flame graph, the width represents the number of bytes allocated.
Tall thin towers: High allocation in a single method (e.g., parsing JSON). This puts pressure on the Young Generation (Eden).
Wide plateaus: A broad code path allocating objects. This is usually structural (e.g., web framework wrapping).
Action: Save this HTML. This is your "healthy" patient. Any future deviation from this shape indicates a regression.
3. Phase II: Leak Hunting (The "Live" Set)
This is the most critical integration of async-profiler. Traditionally, finding leaks required heap dumps (which freeze the JVM). AP allows you to find leaks via sampling without stopping the world.
Objective: Identify objects that are being allocated but not garbage collected.
The Regimen:
Run this hourly in Staging or Production (low overhead ~1-2%).
The Command:
bash
# --live: Only record objects that survived at least 1 GC cycle
# -e alloc: Track allocation events
./profiler.sh -d 300 -e alloc --live -f leak_hunt_$(date +%s).html <pid>
How it works:
AP hooks into the JIT compiler to intercept object allocation. If an object is allocated and subsequently collected, AP discards the stack trace. If the object survives (exceeds the TLAB size or survives a GC), the stack trace is recorded.
Analysis:
Open the resulting Flame Graph.
If you see significant activity, those are objects that are staying in memory.
False Positives: You will see caches and singletons. Ignore those.
True Leaks: Look for business logic objects (e.g., UserSession, OrderRequest, byte[] from file reads) accumulating.
4. Phase III: The "Leak Verification" (Triggered)
If Phase II identifies a suspect, do not dump the heap yet. Trigger a specific profile to verify the retention path.
Scenario: You suspect UserSession objects are leaking.
The Regimen:
Use the Interceptor method in Async-profiler to trace specific class retention.
The Command (using Java API):
Inject a small agent or use the AP Java API to trace the lifecycle of the specific class.
java
// Conceptual logic for a custom agent or aspect
// Track when UserSession is created and when it finalize() is called
However, keeping it strictly to CLI tools, we move to JFR (Java Flight Recorder) for correlation.
The Command:
Start a JFR recording focusing on object allocation and GC roots.
Analyze the JFR using JDK Mission Control (JMC) to look at "Live Objects" statistics.
5. Phase IV: The "Nuclear Option" (Heap Dump Analysis)
If the leak is subtle and AP + JFR cannot pinpoint the GC root, you must dump the heap. Do not do this in production unless absolutely necessary (it causes a full STW pause, scaling with heap size, often 30s-60s for 4GB+ heaps).
The Workflow:
Dump:
bash
jcmd <pid> GC.heap_dump /tmp/heap.hprof
Analyze: Pull the file locally. Use Eclipse Memory Analyzer (MAT) or IntelliJ IDEA Profiler.
Technique:
Run "Leak Suspects Report".
Run "Top Components".
Dominator Tree: Identify the largest objects.
Merge Shortest Path to GC Root: This tells you who is holding the reference.
6. Automated Regimen Summary
Here is a cron-based regimen you can implement on your servers (Staging/Canary recommended).
Frequency
Action
Tool
Command / Config
Goal
Every 1h
Allocation Sampling
Async Profiler
-e alloc -d 30
Monitor allocation "baseline" (Young Gen pressure).
Every 6h
Live Object Sampling
Async Profiler
-e alloc --live -d 60
Detect objects surviving GC (Leak Detection).
Continuous
System Metrics
Prometheus/Node Exporter
Monitor JVM Memory Pools
Correlate spikes in Old Gen with deployment timestamps.
On-Demand
Object Allocation Trace
Async Profiler
-e alloc -e Gc
Correlate high allocation with GC pauses (Latency correlation).
7. Interpreting the Data (The "So What?")
When you look at the generated Flamegraphs, follow this decision tree:
Is the flame wide at the top (User Code)?
Diagnosis: Your business logic is allocating too much.
Fix: Optimize data structures, reduce boxing (primitives vs objects), use object pooling (rarely recommended now, but possible), or stream processing.
Is the flame wide at the bottom (JDK/Interpreter)?
Diagnosis: High JVM overhead.
Fix: Check for excessive Class Loading or JIT compilation cache pressure.
Is the "Live" flame growing over time?
Diagnosis: Memory Leak.
Fix: Identify the accumulating class in the flame graph. Verify if it is a Cache (intended) or a List (unintended). If it's a List/Map growing indefinitely, find the insertion point and ensure removal logic exists.
Are there distinct "spikes" in allocation correlating with traffic?
Diagnosis: Insufficient Young Gen sizing.
Fix: If allocation rate is healthy but GC frequency is too high, increase -Xmn (Young Gen size) to allow more objects to die young (the "die fast" principle).
Summary
The "Regimen" is simply:
Baseline with standard alloc profiling.
Detect with --live alloc profiling.
Verify with JFR or Heap Dumps.
Automate the first two steps so you have data before the OutOfMemoryError occurs.