Catch Leak If You Can! - Paulina Szklarska - Medium
We have an inner class inside activity. In this inner class, we make some action delayed by 10 minutes. How long does the activity outside inner class lives? At least as long as the inner class. This is caused by a fact that inner class has a full access to the top-level class, including fields and methods (and context!). So what will happen if we run Handler
delayed by 10 minutes inside inner class and close the InnerClassLeakActivity
? Well, as long as the Handler
lives, InnerClass
must also live, and InnerClassLeakActivity
also. So we'll have a memory leak for 10 minutes. It doesn't sound very bad, but imagine you have some repeating task in that Handler and your activity has a lot of heavy resources (images). This may end pretty bad.
What would be a fix for that? Using static nested class. It has its own lifecycle, independent from top-level class and thus doesn't cause potential memory leaks. To summarize:
- don't make non-static nested classes that may live longer than Activity
- try to replace non-static nested class with inner class
Read full article from Catch Leak If You Can! - Paulina Szklarska - Medium
No comments:
Post a Comment