Tracing simple memory leak around RecyclerView using LeakCanary

Figuring out the object references under the hood and the importance of LeakCanary

Preface

This article is mostly meant for novice to mid level Android programmers, who haven’t really digged into LeakCanary yet. I myself used it for the first time recently after delving into Android development for a year. And I am pleasantly surprised how powerful this tool is. This is definitely a must-include tool in every project. At the same time, I was surprised how Android maintains references under the hood for RecyclerViews. With naive expectation that RecyclerView itself should avoid circular references, you can easily fall into a trap of memory leaks. (And that's exactly the kind of reason that Square guys implemented LeakCanary and everybody should use it)

How to use LeakCanary

It’s pretty simple to use LeakCanary. As instructed in the README section, you just need to 1. describe dependency in gradle and 2. write a few lines in your Application subclass. And then LeakCanary will alert you of the memory leak in your debug build.

A case you can easily produce memory leak

Let’s look at a case where I was quite surprised to cause memory leak. The basic structure of the code looks like this :

Image for post
Image for post
Application Structure
Image for post
Image for post
Object reference path by LeakCanary
Image for post
Image for post
Actual App Structure

Solution 1

A simple solution is to shorten the lifetime of adapter to match with the one of the Activity. Showing only the diff of before-after in the sample code below.

Image for post
Image for post
Structure without adapter reference

Solution 2

Another simple solution is to call recyclerView.adapter = null from onDestroyView.

Image for post
Image for post
Structure after nulling out adapter

Summary

Even though I think solution 1 is by-the-book approach, it has a shortcoming that you can not let adapter to hold temporary status. If you need adapter to maintain temporary status, then probably better to pick solution 2.

Coding in Swift, want to learn Flutter, a Dad, a Rock Climber, learning Parkour and Guitar

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store