Home » Android » Android memory leak example from Google I/O

Android memory leak example from Google I/O

Posted by: admin May 14, 2020 Leave a comment


I just had a look at the google io video “memory management for android”. Slides are available here http://dubroy.com/memory_management_for_android_apps.pdf. The memory leak example is on slide 36.

I do not understand why this causes a leak after orientation change. I do understand that leak is an inner class and has a reference to the outer class. Also, I do understand that the static variable “leak” references the “Leaky” object..thus the whole activity. I think that’s special because of the static keyword. Static variables have a certain memory and are probably not gc’ed (at least as long as the application runs)?!?

Well, what happens on oriantation change? A new activity instance is created and the activities onCreate is called. leak == null is false. Leak still points to the “old” activity. That’s a leak. The old activity cant be gc’ed, right?

Why does memory usage increase with every oriantation change? In my (wrong) understanding I’d assume that just the first activity can’t be gc’ed. The other activites that are created because of oriantation change can be gc’ed because they aren’t referenced by that static variable “leak”.

However..obviously..I’m completely wrong!

How to&Answers:

A classic explanation of the orientation change Context memory leak from Google blog. You were most of the way there, I think, noting static reference of the inner to the outer class.


You don’t understand because you made a critical error. leak == null is true in the newly created activity. leak doesn’t still point to the “old” activity.

Why? I thought leak was static you ask. Well. . .

So, first time around, the activity is created, leak is null, then onCreate() and leak now references a Leaky object. If I create more instances of that activity, their leak’s will not be null and reference that same object.

But, what happens when you flip orientation is that the activity is destroyed. So, there is no existing instance of an activity object. Android then creates a new activity, where leak is null (because as far as Android is concerned, no other instance of the activity exists).

However, to the garbage collector, someone does hold a reference to the destroyed activity, namely its inner Leaky class. So it won’t free that memory. Hence, as you continue to change orientation, you keep leaking an activities worth of memory.