Leak Canary, what is it?

Erman Derici
Huawei Developers
Published in
3 min readMay 10, 2024
Leak Canary

Greetings,

In this article, I will go over the basics of Leak Canary and explain how we can use it to improve the performance of our Android app.

Introduction

While developing our Android apps, we all have encountered some noticeable performance issues. These can range from simple memory leaks to major Application Not Responding (ANR) issues. Smaller memory leaks are harder to detect than ANR issues, and manually going over your code to see which component causes the memory leak is a time consuming task. Luckily, we have Leak Canary to help us.

Leak Canary

Leak Canary is a simple dependency that monitors your app’s performance during runtime, creating a neat log for you to analyse.

To add Leak Canary to your app, you can simply add this dependency:

dependencies {
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
}

Please note that this is a debug implementation, as Leak Canary is used to find the memory leaks before release and during development phase.
And that’s it, you have successfully added Leak Canary to your app.

How can I use it?

Leak Canary monitors your app during runtime and constantly updates its logs for you analyse. You can see these notifications pop-up occasionally:

Leak example
Leak example

This means that there were multiple memory leaks. Leak Canary waits until the memory leaks reach a certain threshold and dumps the Java heap.

Leak Canary detects these leaks:

  • Destroyed Activity
  • Destroyed Fragment
  • Destroyed Services
  • Destroyed Fragment Views
  • Cleared View Models

You can click on the notification or open Leak Canary manually to see the leaks:

Leak Canary Leaks

Here you can see the detailed logs of Leak Canary and see the leaks present in the app.
Some references here are easier to recognize and fix on your own, but there might be more obscure reasons why your app has leaks. To find out, you can use a custom implementation to tell Leak Canary what objects and what instances are expected to be garbage collected and should be observed. However, that is a bit of a detailed explanation that is out of the scope of this article. You can learn more about this process in the official documentation, linked in the references section.

Leak details

Conclusion

We have learned how to integrate Leak Canary to our app and seen how it reports the found memory leaks.
The most common leaks are references to views or activities in unrelated classes, which are somewhat easier to fix. But remember, Leak Canary is a tool to locate these issues, it does not fix them for you.

--

--