Memory leaks and LeakCanary

Learn to find Android memory leaks with LeakCanary, read a leak trace, and fix static references, unregistered listeners, collectors and view bindings. About 25 minutes.

Why it matters

  • A single static reference to an Activity in a Kotlin object or companion object can keep the whole View tree in memory for the life of the process. Repeated across screens, these leaks raise memory use and can end in OutOfMemoryError after 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.

PatternWhat holds the objectFix
object / companion object stores an Activity or ContextStatic field on the classStore applicationContext, or do not store it at all
registerReceiver or a listener without unregisterThe system service or the object you registered withPair register and unregister in matching callbacks (onStart/onStop)
Coroutine or Flow collector outlives the ViewA coroutine in GlobalScope or another long-lived scopeCollect in viewLifecycleOwner.lifecycleScope with repeatOnLifecycle
Fragment view binding not clearedFragment instance, then binding, then the View treeSet 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.

A leaked Activity and how LeakCanary finds it
A leaked Activity and how LeakCanary finds it A GC root reaches a companion object that lives with the process and holds a destroyed Activity, so the garbage collector cannot free it; LeakCanary notices the Activity is still retained after a GC, dumps the heap and reports the leak trace from GC root to Activity. HOLDS CAN'T FREE IT RETAINED AFTER GC HEAP DUMP GC root static field companion object lives with the process Destroyed Activity and its whole View tree Garbage collector frees unreachable objects LeakCanary watches destroyed objects Leak trace GC root → companion → Activity
A long-lived reference keeps the destroyed Activity reachable, so it cannot be freed; LeakCanary shows the chain that holds it.

Notes

  • Add LeakCanary with debugImplementation only. Heap dumps freeze the app while they are written and produce large files; it must never ship in release.
  • Watched automatically: destroyed Activity, Fragment, Fragment View, cleared ViewModel and destroyed Service instances. For your own objects call AppWatcher.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: NO node and the first Leaking: YES node.
  • Fragment view binding: declare private var _binding: FragmentChatBinding? = null and set it to null in onDestroyView(). Forgetting this keeps the old View tree alive while the Fragment sits on the back stack.
  • Collect Flows into UI with viewLifecycleOwner.lifecycleScope.launch and viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED). Never use GlobalScope for View-bound work.
  • A Kotlin object or companion object that stores an Activity, View or Context is a common leak. Android Lint flags many of these as StaticFieldLeak. Use applicationContext for long-lived holders.
  • Pair registerReceiver with unregisterReceiver in matching callbacks. Android 13 (API 33) added RECEIVER_EXPORTED and RECEIVER_NOT_EXPORTED; use ContextCompat.registerReceiver and pass one of them.
  • Delayed Handler.postDelayed callbacks and lambdas that capture an Activity keep it alive until they run. Remove pending callbacks in onDestroy or use a lifecycle-aware coroutine instead.
  • In UI tests, add androidTestImplementation of leakcanary-android-instrumentation and use the DetectLeaksAfterTestSuccess rule (or LeakAssertions.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
    }
}
  • _binding is nulled in onDestroyView, so a Fragment on the back stack no longer holds the old View tree.
  • viewLifecycleOwner.lifecycleScope is cancelled when the view is destroyed; repeatOnLifecycle(STARTED) also stops collecting in onStop and restarts in onStart.
  • The adapter outlives the view as a Fragment field, so it is detached from the RecyclerView in onDestroyView; otherwise the adapter's observer list keeps the old RecyclerView alive.

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

News app: memory grows with every article opened
  • Crash reports showed OutOfMemoryError on low-RAM devices, always after long reading sessions with many screens opened.
  • An AnalyticsTracker Kotlin object kept a currentActivity field so it could read screen names, which kept the last destroyed Activity and its View tree alive.
  • LeakCanary in debug showed the GC root as the static AnalyticsTracker.INSTANCE field, then currentActivity, then the destroyed ArticleActivity marked Leaking: YES.
The fix
  • Removed the Activity field. The tracker now takes applicationContext at init and receives the screen name as a String parameter on each event.
  • Added DetectLeaksAfterTestSuccess to 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.
Messaging app: old chat views kept alive after navigation
  • LeakCanary reported a retained Fragment View every 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-null lateinit binding, 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 binding to the destroyed RecyclerView.
The fix
  • Moved the collector to viewLifecycleOwner.lifecycleScope with repeatOnLifecycle(Lifecycle.State.STARTED), so it is cancelled with the view.
  • Switched to a nullable _binding cleared in onDestroyView(), and set the RecyclerView adapter to null there.
  • LeakCanary no longer reported a retained Fragment View after 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 debugImplementation only; 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. GlobalScope is never cancelled, and the Fragment's lifecycleScope survives view destruction while the Fragment is on the back stack. Use viewLifecycleOwner.lifecycleScope with repeatOnLifecycle. 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 applicationContext or pass the data you need as parameters.
  • Registering and unregistering in mismatched callbacks or components. If a Fragment registers a receiver or listener in onStart and the Activity unregisters it in onDestroy, 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

  1. Add debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14") to app/build.gradle.kts (or the current version from the LeakCanary docs). Confirm it is in the debug configuration, not implementation.

  2. Create a LeakyFragment that keeps its view binding in a lateinit var and never clears it in onDestroyView. Also add a companion object that stores the hosting Activity in a var.

  3. Run the debug build, open LeakyFragment, then navigate to another Fragment (so LeakyFragment goes 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.

  4. 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 where Leaking: NO turns into Leaking: YES.

  5. Fix both leaks: (a) switch to a nullable _binding set to null in onDestroyView, (b) remove the Activity from the companion object.

  6. 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.

Next: ANRs: causes and fixes