Memory leaks and LeakCanary
Why it matters
- A single static reference to an
Activityin a Kotlinobjectorcompanion objectcan keep the whole View tree in memory for the life of the process. Repeated across screens, these leaks raise memory use and can end inOutOfMemoryErrorafter long sessions. - Senior Android interviews often ask you to read a LeakCanary leak trace and name the GC root, the reference chain, and the link to break.
- Coroutine and Flow collectors launched in
GlobalScope(or in a scope that outlives the view) that write into a View keep that View reachable after the Fragment's view is destroyed. - LeakCanary turns "memory keeps growing" into a concrete reference chain. ANR traces and Perfetto (other lessons in this module) show timing, not which reference keeps an object alive.
The simple explanation
- A hotel front desk (the garbage collector) can only free a room when no key card (reference) for it is still out.
- If a guest checked out but a key is still in a desk drawer, the room stays occupied. That is a leak.
- LeakCanary is the auditor who checks rooms a few seconds after checkout and finds keys that should have been handed back.
- The auditor's report lists the desk (GC root), each drawer it went through (intermediate references), and the room (leaked object).
- Your job is to take one key out of the chain: clear the reference, unregister the listener, or cancel the collector.
What is a memory leak in Android, and how does LeakCanary find it? A memory leak is an object the app no longer needs, such as a destroyed Activity, that the garbage collector cannot free because something long-lived still references it. LeakCanary finds these in debug builds. You add only the debugImplementation dependency com.squareup.leakcanary:leakcanary-android; it installs itself with no code.
LeakCanary automatically watches destroyed Activity instances, destroyed Fragment instances, destroyed Fragment View instances, cleared ViewModel instances and destroyed Service instances. It holds each one through a weak reference. If the object is still reachable after 5 seconds and a garbage collection, it counts as retained. When enough objects are retained (5 while the app is visible, 1 once it goes to the background), LeakCanary dumps the heap to an .hprof file, analyses it with its Shark library, and finds the shortest path of references from a GC root to each retained object.
The result is a leak trace, shown through a notification, in the separate Leaks launcher app, and in Logcat. It reads top-down: GC root, then intermediate references, then the leaked object. Each node is marked Leaking: NO, YES or UNKNOWN, and suspect references are underlined. The bug is in the references between the last Leaking: NO node and the first Leaking: YES node. The fix is always to break one link in that part of the chain.
| Pattern | What holds the object | Fix |
|---|---|---|
object / companion object stores an Activity or Context | Static field on the class | Store applicationContext, or do not store it at all |
registerReceiver or a listener without unregister | The system service or the object you registered with | Pair register and unregister in matching callbacks (onStart/onStop) |
| Coroutine or Flow collector outlives the View | A coroutine in GlobalScope or another long-lived scope | Collect in viewLifecycleOwner.lifecycleScope with repeatOnLifecycle |
| Fragment view binding not cleared | Fragment instance, then binding, then the View tree | Set binding = null in onDestroyView() |
A key distinction: a Fragment on the back stack keeps its instance but loses its view. Anything the Fragment holds that points at the old view (a binding, an adapter that references views, a collector writing to a view) keeps that dead View tree alive until the Fragment is destroyed. viewLifecycleOwner.lifecycleScope is cancelled when the view is destroyed, which is the right scope for UI-bound collection.
Notes
- Add LeakCanary with
debugImplementationonly. Heap dumps freeze the app while they are written and produce large files; it must never ship in release. - Watched automatically: destroyed
Activity,Fragment, FragmentView, clearedViewModeland destroyedServiceinstances. For your own objects callAppWatcher.objectWatcher.expectWeaklyReachable(obj, "reason")when they should be gone. - A retained object is not yet a confirmed leak. LeakCanary dumps the heap after 5 retained objects while the app is visible, or 1 when the app goes to the background. You can also tap its notification to dump now.
- Read a leak trace from the GC root down. The leak is in the references between the last
Leaking: NOnode and the firstLeaking: YESnode. - Fragment view binding: declare
private var _binding: FragmentChatBinding? = nulland set it tonullinonDestroyView(). Forgetting this keeps the old View tree alive while the Fragment sits on the back stack. - Collect Flows into UI with
viewLifecycleOwner.lifecycleScope.launchandviewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED). Never useGlobalScopefor View-bound work. - A Kotlin
objectorcompanion objectthat stores anActivity,VieworContextis a common leak. Android Lint flags many of these asStaticFieldLeak. UseapplicationContextfor long-lived holders. - Pair
registerReceiverwithunregisterReceiverin matching callbacks. Android 13 (API 33) addedRECEIVER_EXPORTEDandRECEIVER_NOT_EXPORTED; useContextCompat.registerReceiverand pass one of them. - Delayed
Handler.postDelayedcallbacks and lambdas that capture anActivitykeep it alive until they run. Remove pending callbacks inonDestroyor use a lifecycle-aware coroutine instead. - In UI tests, add
androidTestImplementationofleakcanary-android-instrumentationand use theDetectLeaksAfterTestSuccessrule (orLeakAssertions.assertNoLeaks()) so a leak fails the test.
Code example
This Fragment shows the leak-free pattern: a nullable view binding cleared in onDestroyView, and a Flow collected through viewLifecycleOwner.lifecycleScope with repeatOnLifecycle, so collection stops when the view stops and the coroutine is cancelled when the view is destroyed.
class ChatFragment : Fragment() {
private var _binding: FragmentChatBinding? = null
private val binding get() = _binding!! // only valid between onCreateView and onDestroyView
private val viewModel: ChatViewModel by viewModels()
private val adapter = MessageAdapter()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentChatBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.chatList.adapter = adapter
viewLifecycleOwner.lifecycleScope.launch {
// Collects while the view is at least STARTED, stops in onStop
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.messages.collect { messages ->
adapter.submitList(messages)
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
binding.chatList.adapter = null // the RecyclerView would otherwise stay referenced by the adapter
_binding = null // releases the View tree while the Fragment is on the back stack
}
}_bindingis nulled inonDestroyView, so a Fragment on the back stack no longer holds the old View tree.viewLifecycleOwner.lifecycleScopeis cancelled when the view is destroyed;repeatOnLifecycle(STARTED)also stops collecting inonStopand restarts inonStart.- The adapter outlives the view as a Fragment field, so it is detached from the
RecyclerViewinonDestroyView; otherwise the adapter's observer list keeps the oldRecyclerViewalive.
Run the idea in plain Kotlin
class Listener(val name: String)
class EventBus {
private val listeners = mutableListOf<Listener>()
fun add(l: Listener) { listeners.add(l) }
fun remove(l: Listener) { listeners.remove(l) }
fun fire() {
for (l in listeners) {
println("Event delivered to " + l.name)
}
}
fun size(): Int = listeners.size
}
fun main() {
val bus = EventBus()
val l1 = Listener("ScreenA")
val l2 = Listener("ScreenB")
bus.add(l1)
bus.add(l2)
println("Registered listeners: " + bus.size())
bus.fire()
// ScreenA is destroyed but nobody called remove -> leak
println("After ScreenA destroyed, still registered: " + bus.size())
// Fix: call bus.remove(l1) in ScreenA's matching teardown callback
bus.remove(l1)
println("After proper cleanup: " + bus.size())
bus.fire()
}Expected output:
Registered listeners: 2
Event delivered to ScreenA
Event delivered to ScreenB
After ScreenA destroyed, still registered: 2
After proper cleanup: 1
Event delivered to ScreenB
In production
- Crash reports showed
OutOfMemoryErroron low-RAM devices, always after long reading sessions with many screens opened. - An
AnalyticsTrackerKotlinobjectkept acurrentActivityfield so it could read screen names, which kept the last destroyedActivityand its View tree alive. - LeakCanary in debug showed the GC root as the static
AnalyticsTracker.INSTANCEfield, thencurrentActivity, then the destroyedArticleActivitymarkedLeaking: YES.
- Removed the
Activityfield. The tracker now takesapplicationContextat init and receives the screen name as aStringparameter on each event. - Added
DetectLeaksAfterTestSuccessto the instrumented UI tests for the main flows, so a new leak in those flows fails CI. - Confirmed with LeakCanary that opening and closing articles no longer retains any
Activity.
- LeakCanary reported a retained Fragment
Viewevery time the user opened a chat and then navigated to another screen. - The chat Fragment collected messages with
lifecycleScope(the Fragment's own lifecycle) into a non-nulllateinitbinding, and never cleared the binding. While the Fragment sat on the back stack, the collector and the field both kept the old View tree alive. - The leak trace went from the Fragment instance through
bindingto the destroyedRecyclerView.
- Moved the collector to
viewLifecycleOwner.lifecycleScopewithrepeatOnLifecycle(Lifecycle.State.STARTED), so it is cancelled with the view. - Switched to a nullable
_bindingcleared inonDestroyView(), and set theRecyclerViewadapter tonullthere. - LeakCanary no longer reported a retained Fragment
Viewafter repeating the navigation several times.
Common mistakes
- Adding LeakCanary to the release build. Heap dumps freeze the app and write large files to storage. Use
debugImplementationonly; in release, rely on lint, code review and your debug and test runs. - Forgetting to clear the binding in onDestroyView. The Fragment instance holds the binding, which holds the entire View tree. A Fragment on the back stack keeps that dead tree alive until it is destroyed. Null the binding in
onDestroyView. - Collecting a Flow into a View in GlobalScope or the Fragment's own lifecycleScope.
GlobalScopeis never cancelled, and the Fragment'slifecycleScopesurvives view destruction while the Fragment is on the back stack. UseviewLifecycleOwner.lifecycleScopewithrepeatOnLifecycle. A ViewModel should never hold Views at all. - Storing an Activity, View or Context in an object or companion object. These are static and live as long as the process. Use
applicationContextor pass the data you need as parameters. - Registering and unregistering in mismatched callbacks or components. If a Fragment registers a receiver or listener in
onStartand the Activity unregisters it inonDestroy, the Fragment stays referenced in between. Pair register and unregister in matching callbacks of the same component. - Treating LeakCanary reports as "just debug". A leak found in a debug build is the same reference bug in release. Fix it before merge.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does LeakCanary detect a memory leak?”
“What are the most common memory leak patterns in a Kotlin Android app?”
“How do you handle Fragment view binding correctly?”
“What is the difference between viewModelScope and viewLifecycleOwner.lifecycleScope, and how does each relate to leaks?”
Quiz
Which coroutine scope should you use to collect a Flow into a Fragment's UI?
What does LeakCanary do before it reports an object as retained?
Which of these is NOT a common Android memory leak pattern?
Where should you set a Fragment's view binding to null?
0 of 4 answered
Mini task
15-minute exercise: find and fix a Fragment leak with LeakCanary
-
Add
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")toapp/build.gradle.kts(or the current version from the LeakCanary docs). Confirm it is in thedebugconfiguration, notimplementation. -
Create a
LeakyFragmentthat keeps its view binding in alateinit varand never clears it inonDestroyView. Also add acompanion objectthat stores the hostingActivityin avar. -
Run the debug build, open
LeakyFragment, then navigate to another Fragment (soLeakyFragmentgoes to the back stack) and press Home to send the app to the background. Wait for the LeakCanary notification, or tap it to dump the heap. -
Open the Leaks app (installed next to your app) or filter Logcat by
LeakCanary. Find the GC root at the top, the reference chain, and the node whereLeaking: NOturns intoLeaking: YES. -
Fix both leaks: (a) switch to a nullable
_bindingset tonullinonDestroyView, (b) remove theActivityfrom thecompanion object. -
Repeat step 3 a few times. Confirm no new leak is reported.
Done condition: LeakCanary reports no leaks after navigating away from LeakyFragment and backgrounding the app three times, and the companion object no longer holds an Activity.