🦈 Shark Heap Analysis - LeakCanary's Detective at Work

 

Introduction

In Part 3, we saw how LeakCanary boldly freezes your app to capture a heap dump. But a .hprof file is just raw binary data — unreadable to humans. Enter Shark, LeakCanary’s analysis engine. Shark parses the dump, builds a navigable object graph, and uncovers the exact reference chains that keep your objects alive.

This is where leaks stop being mysterious and start becoming actionable.

⚙️ Shark’s Workflow

1. Parsing the Heap Dump

Shark uses Shark Hprof (built on Okio) to stream through .hprof records efficiently.

val heapGraph = Hprof.openHeapGraph(heapDumpFile)
  • Converts raw data into a HeapGraph.
  • HeapGraph exposes classes, objects, fields, and references.

2. Building the Heap Graph

HeapGraph lets you query memory like a database:

val activityClass = heapGraph.findClassByName("com.example.LeakyActivity")
val instances = activityClass.instances
  • You can traverse references between objects.
  • This graph is the foundation for leak detection.

3. Finding Leaks

Shark’s HeapAnalyzer orchestrates leak detection:

  1. Identifies suspected leaking objects (from ObjectWatcher).
  2. Finds shortest paths from GC roots to those objects.
  3. Applies ReferenceMatchers to filter known library/framework leaks.
  4. Builds LeakTrace reports.

Sample LeakTrace:

┬───
GC Root: System class

├─ android.view.inputmethod.InputMethodManager
Leaking: NO
InputMethodManager.mLastSrvView
├─ com.example.LeakyActivity
Leaking: YES (Activity was destroyed)

4. Retained Size Calculation

Shark uses a dominator tree algorithm to compute retained size:

  • Shows how much memory would be freed if the leaking object were collected.
  • Helps prioritize leaks (a retained Activity > a small View).

📊 Diagram: Shark Analysis Flow

Heap Dump (.hprof) → Shark Hprof → HeapGraph → HeapAnalyzer → LeakTrace → Developer Fix

🚨 Why Shark Matters

  • Transforms raw data into insights.
  • Automates leak detection with shortest path analysis.
  • Categorises leaks into app, library, and framework.
  • Empowers developers to fix leaks before they hit production.

🔮 Coming Next

In Part 5, we’ll explore Dominator Tree & Retained Size — the algorithmic heart of Shark that quantifies the impact of leaks.

Comments

Featured Articles

Optimize Jetpack Compose: Performance & Best Practices

JIT vs AOT Compilation | Android Runtime

From ‘Master’ to ‘Main’: The Meaning Behind Git’s Naming Shift

Play Store Uploads with Fastlane Supply - 4

Cracking Android SDE2/SDE3 Interviews in 2026: Deep Dives, Code, Follow-ups

Android Device Security: Sandboxing, Rooting, and Attestation Explained