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 s. With naive expectation that 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 subclass. And then LeakCanary will alert you of the memory leak in your debug build.

However, as straight-forward as it sounds, there was one pitfall I got into. If you are like me and prefers to press Debug button instead of Run button on Android Studio, LeakCanary doesn’t run while you are debugging. You have to stop the debugging, and start the installed debug build from the launcher.

I have summarized this flow into a video, if this helps :

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 :

Application Structure

shows and it's provides custom s. As simple as it can be, right? One thing that deviates from simplest structure is that the keeps reference to the . This reference is meant to reuse even after is refreshed due to rotation etc. We are showing on top of the , so I think it is a sensible option to match the lifetime of 's to the one of the as opposed to the .

The corresponding part of the code looks as follows :

This structure looks memory leak safe because there doesn’t seem any circular references. However, my naiive expectation is false...

The object reference path provided by LeakCanary looks like this:

Object reference path by LeakCanary

To my surprise, this diagram tells me that holds an indirect reference to through . This is not a reference we made ourselves. This is a “hidden” reference, if we may call it.

So, the actual structure with this “hidden” reference (indicated by the dashed lines) is something like the next diagram.

Actual App Structure

You can see there is a beautiful circular reference from => => => => and so on... Rotation happens, and gets recreated, but since still lives after rotation and keeps indirect reference to the old , the old will never reclaimed by GC and leaks.

As a side note, the is always recreated after rotation and reference from to the old through Android-Kotlin extension never stays after rotation (indicated by the red cross in the diagram). That's how Android works.

Solution 1

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

Every time when rotation happens, you will ditch the old that holds an indirect reference to the old .

If we look at the structure, we don’t have the circular reference anymore, because we removed link from to .

Structure without adapter reference

The cons of this approach is that you cannot save the temporary state in the , because the is initialized at every rotation. We have to save the temporary state somewhere else, and let the to fetch the state after every initialization.

Solution 2

Another simple solution is to call from .

Actually, I was surprised that this approach works. Even if you null out the reference from to , as long as the has a reference to , you still have circular reference. The only way I can comprehend is that Android actually nulls out the reference from to the as well when you null out the reverse reference, thereby eliminating the circular reference entirely.

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 to hold temporary status. If you need to maintain temporary status, then probably better to pick solution 2.

In any case, you want to prepare your mental model including the “hidden” references, in order to flexibly handle such memory leak situation. And LeakCanary can really help you shaping this mental model. Otherwise, it was impossible for me to know that there is such hidden references around without reading the internal code.

If you are interested, I put the sample code in GitHub. You can follow git tags to get different stage of the code. (adapter-memory-leak tag shows the code that causes memory leak, fix-adapter-memory-leak-1 tag shows the solution 1 to treat the memory leak, etc.)

Another interesting point I want to note is that this type of memory leak does not occur with . Your can hold reference to and it causes no memory leak. The way the set "hidden" references should be a bit different from how does.

That is it. Bye bye memory leaks. Long live LeakCanary!!

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