In the Android development process, we may encounter a crash Oom exception, in the face of such an exception we are both familiar and hated, because there are many reasons for oom, such as loading pictures too large, a class that is no longer used by GC and so on. In this article we will analyze one of the scenarios that caused the oom, the memory leak caused by handler.
This article is divided into 3 parts:
1.Handler Memory Leak Example description and principle clarification
2. Problem verification (skip directly if you feel cumbersome)
3.Handler Memory Leak resolution
1.Handler Memory Leak Example Description and principle clarification
When there is a delayed task in handler or a queue of tasks waiting to be executed too long, because the message holds a reference to handler, and handler holds a potential reference to the external class, this referential relationship remains until the message is processed, causing the activity to not be recycled by the garbage collector. Causes a memory leak. Remember that we used to confidently use the following beautiful and concise code is not.
Not afraid you scare, to tell you the truth, this code has caused a memory leak ... Don't believe it. We use the Android Lint tool to check the code for this class:
Let's face it, why is that so? Non-static inner classes and anonymous inner classes in Java implicitly hold external references to the current class, because handler is a non-static inner class, so it holds an implicit reference to the current activity, and if Handler is not released, The external reference that it holds is also impossible to release, when an object sentence does not need to be reused, it should be recycled, and another object that is being used holds its reference so that it cannot be recycled, which causes the object to be recycled to remain in the heap memory. This creates a memory leak (the above example is the reason). Eventually, it caused the oom ... Let's take a clear piece of code and we'll use Mhandler to send a delay message:
Analysis: When we execute the Handleractivity interface, the deferred message is present in the main thread message queue for 5 minutes before it is processed, and the message contains the handler reference, and the handler we create is an instance of an anonymous inner class. It holds a reference to an external handleractivity, which causes the handleractivity to fail to be recycled, causing many of the resources handleractivity hold to be recycled, causing a legendary memory leak.
2. Problem verification (skip directly if you feel cumbersome)
To further verify the memory leak problem, we create an int array in the class that allocates a memory size of 2m, and then we use DDMS to look at the heap memory and then recycle it using GC to see if the memory will change:
The first time you start the app, head memory is 12.5M, already allocated content (allocated): 8.5M, free memory: 4M, we frequently click the GC button, memory has not changed significantly, now we click on the phone back to health, launch the application, and then re-enter, Also check head memory:
We found head memory: 20.5m,allocated:16.5m,free:4m, heap memory and already allocated memory nearly doubled, we continue to frequently click the GC to see if it can be recycled. The memory does not change significantly, now we continue to click on the phone back to health, launch the application, and then re-enter, again detect head memory:
We found head memory: 28.5m,allocated:24.5m,free:4m, heap memory and allocated memory increased, and no matter how we clicked on the GC to reclaim memory, there was no significant change in memory, and every time the page was started, the memory increased by a factor. This means that there is a memory leak problem in cases where a class is created and not destroyed. We use the Mat tool to further verify the problem, we look at a set of histogram data and Dominator tree data, first of all histogram data:
Dominator Tree Data:
There are three identical handleractivity and internal classes, which is enough to show that Handleractvity is only created and not destroyed, which means that the memory leak caused by handler really exists.
3.Handler Memory leak resolution
The idea of solving this problem is to use static internal classes and inherit handler (or you can store them separately as a class file). Because static inner classes do not hold references to external classes, they do not cause memory leaks for external class instances. When you need to invoke external activity in a static inner class, we can use a weak reference to handle it. Also on the same need to set runnable to static member properties. The code that will not cause a memory leak after modification is as follows:
[Java] View Plain Copy package com.zejian.handlerlooper; import android.app.activity; import android.os.bundle; import android.os.handler; import android.os.message; import java.lang.ref.weakreference; /** * created by zejian on 16/3/6. */ public class handleractivity extends activity { //Create an int array of 2M size int[] datas=new int[1024*1024*2]; // handler mhandler = new handler () { // @Override // public void Handlemessage (message msg) { // super.handlemessage (msg); // } // }; /** Create static internal classes */ private static class myhandler extends Handler{ //is recycled when it holds a weak reference handleractivity,gc. private final WeakReference< handleractivity> mactivty; public MyHandler (handleractivity activity) { mActivty =new WeakReference<HandlerActivity> (activity); } @ override &NBSP;&NBSp; public void handlemessage (message msg) { handleractivity activity= Mactivty.get (); Super.handlemessage (msg); if (activity!=null) { //Executing business logic } } } private static final runnable myrunnable = new runnable () { @Override public void run () { //execution of our business logic } }; @Override Protected void oncreate (bundle savedinstancestate) { super.oncreate (savedinstancestate); setcontentview (r.layout.activity_handler_leak); myhandler myhandler=new myhandler (this); //resolves a memory leak and sends after 5 minutes delay Myhandler.postdelayed (myrunnable, 1000 * 60 * 5); } } HandlerThe memory leak issue to this analysis to resolve the completion. In fact, there are several cases of memory leak, such as the memory leak caused by multithreading, the memory leak caused by static variables, the memory leak caused by the singleton mode, the anonymous inner class, the leak of registered listener, the memory leak caused by the object in the collection, and the construction adapter. Not using cached Convertview and so on.