Android Studio Profiler

Memory leaks fix via Android Studio profiler đź‘€

How to use profiler to find reasons of memory leak?

Jonathan Mercandalli
by MWM

--

Introduction

What is a memory leak?
When garbage collector cannot free memory.

Symptom?
When memory grow indefinitely, causing weak performances, ANR, or crashes.

Main cause on Android?
Activity destruction, for example when screen rotate.
When a reference of Activity is kept in a “static object”, the memory cannot be free.

Example

Here a leaking activity.

  • listener has a reference to the MainActivity via the lambda
  • onCreate add the listener to a static manager
  • So, MainActivity cannot be garbage collected

At each screen rotation, new Activity is created. The manager is unique. The manager set of listeners will grow keeping activities alive and keeping largeObject alive.

Full project available here: memory-leak-android.

Cause and non-cause of leak

What is a scope?
A scope is a chain of reference.
A root reference is the reference of the scope that retain the scope to be free from the garbadge collector point of view.
A scope is considered as “static” when the root reference is kept on a “static” variable (like singleton).

What cause leak?
When “a reference or a transitive reference” of “an object with lifecycle we want to garbage collect” is kept from “a static scope or a scope that persist the object scope”.

What do not cause leak?
When 2 objects of the same scope are referencing one another.
For exemple, a reference from a “static scope” referencing to another object reference also on a “static scope” (two manager for instance).
For example, a view and the activity that created the view.

Profiler Analysis

Measure

  1. Open the profiler: “AndroidStudio bottom bar” > “Profiler”
  2. Select your process: “SESSIONS +” > “Device” > “App”
  3. Click the memory chart
  4. Run the scenario doing the leak (on the sample, screen rotation)
  5. Capture the heap bump
  6. Inspect result

The profiler automatically detect leaks with a ⚠️ icon 🎉

Profiler

Tips to find leak reason #1 — Arrange by package
Great to find only your classes.

Arrange by package

Tips to find leak reason #2— Sort, Depth, Go to Instance

  • A. Check huge object by sorting
  • B. Find the reason with the reference tab and “nearest” checkbox
  • C. Navigate from reference to reference to find the reference hold
Sort retained size -> Check references -> Find reason

Sources

Highly inspired by this article The easiest way to detect and fix memory leaks using Android Studio Profiler Tool and WeakReference ❤.
Thank you Umair Khalid ❤️

--

--

Jonathan Mercandalli
by MWM
Editor for

Android Lead at MWM. Android is my passion. More about me on mercandalli.com