'Can anyone explain how this memory leak in Java/Android works in detail?
I have been doing Java development for a long time, but I am ashamed to say I still don't have a good grasp on how memory leaks actually takes place. I however have no experience with Android development.
Take the following code for example taken from this presentation:
I have the following questions (please note that I am new to Android, but this example is not primarily focused on Android)
- How is memory leak even possible here ? The author says that its because the inner class is not marked as
staticand it will hold a reference to the outer class.
So if I keep creating objects of the outer class like so:
MainActivity one = new MainActivity();
one.onCreate(bundle);
MainActivity two = new MainActivity();
two.onCreate(bundle);
MainActivity three = new MainActivity();
three.onCreate(bundle);
How does it matter ? If I am not wrong about how static references work, then only one object of LeakClass is created, right ? Unless a separate classloader is involved, right ?
- Is the memory leak only possible here because of how Android works ? If I were to manually create these objects then this would not be a problem right ?
Please help me with an ELI5 explanation here, I am really unable to understand how this works.
Thanks.
Solution 1:[1]
Because LeakClass is an inner class, it has an inherent reference to the instance of the outer class that owns it. Since you're storing that value in a static variable, that means you're storing a reference to the outer class in that static transitively. Storing an Activity in a static is ALWAYS a leak, and ALWAYS a bad idea. Activities aren't singletons, you cannot assume there will only be one of them.
If you don't need that parent reference, you can make it a static inner class. Static inner classes do not have an implicit outer reference, but cannot access member variables of functions of the owning class. Or you can make it a standalone, non-inner class (the two are equally good solutions).
If you do need that parent reference, you cannot store it in a static variable without a leak. Figure out another way to make that data available.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabe Sechan |

