Static inner classes and memory leaks

 

 

        The main reason for memory leaks caused by non-static inner classes: The App may run out of memory due to a large number of memory leaks, causing Crash. If the memory is exhausted, the App will have frequent GC due to insufficient memory space, and each GC is a drain. Blocking the operation from time to time will cause the device to freeze.

       A static instance is created in a non-static inner class, which leads to the life cycle of the instance and the application ClassLoader level, and because the static instance implicitly holds a reference to its outer class, the outer class cannot be released normally, resulting in a leak problem .

(classloader: used to dynamically load a class file into memory, only after the class is loaded into memory, it can be referenced by other classes)

1. The non-static inner class will have an implicit reference to the outer class           

        Non-static (anonymous) inner classes hold references to outer classes, and static inner classes do not hold references to outer classes.

2. There are asynchronous tasks in non-static internal classes, which may cause the corresponding external class memory resources to fail to be released normally        

3. A static instance is created in a non-static inner class, which will cause a memory leak

Solution: Remove implicit references (static (anonymous) inner classes), manually manage object references (modify the construction method of static inner classes, manually introduce its outer class references) when memory is unavailable, do not execute uncontrollable code (Android can be combined with Smart pointer, WeakReference wraps external class instance)

Summary: Not all inner classes can only use static inner classes, only when the life cycle in the inner class is uncontrollable, use static inner classes.

Guess you like

Origin blog.csdn.net/gqg_guan/article/details/130708709