🗂️ Heap Dumping Explained - LeakCanary's Bold Move
Introduction
In Part 2, we explored ObjectWatcher, the silent guardian that tracks destroyed objects. But what happens when ObjectWatcher suspects foul play? LeakCanary doesn’t just shrug — it goes nuclear: it dumps the heap.
Heap dumping is the most dramatic step in LeakCanary’s workflow. It freezes your app, writes a snapshot of memory to disk, and hands it over to Shark for analysis. Let’s break down why, how, and what happens next.
⚙️ What is a Heap Dump?
A heap dump is a binary snapshot of the JVM heap at a given moment. It contains:
- All objects currently in memory.
- Their classes and fields.
- References between objects.
- GC roots (entry points into the object graph).
Think of it as a crime scene photo: everything in memory is captured exactly as it is.
🧑💻 Triggering a Heap Dump
LeakCanary triggers a heap dump when retained objects exceed a threshold:
- 5 retained objects when the app is visible.
- 1 retained object when the app is backgrounded.
Code Example
HeapDumpTrigger.onRetainedObjectsDetected {
heapDumper.dumpHeap()
}This call freezes the app briefly, writes a .hprof file, and resumes execution.
📊 Diagram: Heap Dump Workflow
Retained Objects → Threshold Reached → Heap Dump Trigger → .hprof File → Shark Analysis🚨 Trade‑offs
- App freeze: Heap dumping pauses the app for a few seconds.
- File size: Large heaps produce large
.hproffiles. - Performance impact: Best used in debug builds, not production.
LeakCanary balances these trade‑offs by only dumping when necessary.
🧠 Why Heap Dumps Are Worth It
- They provide ground truth: no guesswork, just raw memory state.
- They enable Shark’s analysis: shortest path finder, dominator tree, leak categorisation.
- They empower developers to fix leaks before they hit production.
🔮 Coming Next
In Part 4, we’ll dive into Shark Heap Analysis — how Shark parses .hprof files, builds a heap graph, and generates actionable leak traces.

Comments
Post a Comment