Android & Jetpack Compose (50 Qs)•Part 2: Compose Internals, Persistence, DI & Background Work (11 - 24)
What are Memory Leaks on Android and how do you detect them using LeakCanary?
senior LevelMemory ManagementDocker & Containers
In Simple Words: A memory leak occurs when an object that is no longer needed (e.g. an Activity destroyed on screen rotation) is retained in memory because an active object holds a strong reference to it:
- Common Causes: Static variables referencing Context, non-static inner classes, long-running coroutines holding Activity references, uncancelled broadcast listeners.
- LeakCanary: A memory leak detection library:
- Hooks into
ActivityLifecycleCallbacks. - On
onDestroy(), wraps the instance in aWeakReference. - If the garbage collector has not reclaimed the weak reference after 5 seconds, LeakCanary triggers a heap dump (
.hprof), analyzes the shortest path from GC Roots, and displays a graphical notification with the exact leaking reference chain!
- Hooks into