Android performance optimization using the mat to analyze memory leak issues

Source: Internet
Author: User

Reprint please indicate this article from Xiaanming's blog (http://blog.csdn.net/xiaanming/article/details/42396507), please respect others ' hard work results, thank you!

We usually in the development of Android applications, a little careless may produce oom, although Java has garbage collector, but also can not prevent memory leaks, memory overflow and other issues, with the progress of technology, mobile device memory is getting bigger, but due to the uneven Android devices, May run in this device well, run on that device to the Oom, these adaptation problems are also more egg-like, such as we run an application normally, run well, suddenly to a certain activity will give you an oom error, You might think that this activity caused a memory leak, would you think there might be a leak inside? Memory leaks are like a time bomb that can crash our application at any moment, so as an Android developer, there is a need to analyze memory leaks, saying here we still have to say what a memory leak is, a memory leak refers to a reference to an object that is no longer being used. Causes the object to not be reclaimed by the garbage collector. Therefore, the garbage collector is an object that cannot reclaim memory leaks. This article uses the DDMS (Dalvik Debug Monitor Server) and the mat (Memory Analyzer tool) tools to take you through the analysis of memory leaks.


Preparation of tools

DDMS is a debugging tool with ADT, please refer to http://developer.android.com/tools/debugging/for DDMS use. Ddms.html, and the mat needs us to install the Eclipse plugin on our own, installation method I will not say more, here is an online installation address: http://download.eclipse.org/mat/1.3/update-site/, Mat can detect memory leaks and reduce memory consumption, and it has a very powerful dump capability for parsing heap memory space.


How to detect memory leaks

1. Using DDMS to detect memory leaks

Open the Devices view, select the application process we need to analyze, click the Updata heap button


Then open DDMS, select the Heap tab, then click the Cause GC button, click Cause GC is manually trigger the Java garbage collector, as


If we want to test whether an activity has a memory leak, we can repeatedly enter and exit the activity, and then manually trigger a few garbage collection, observed in the column of the data object in the size of total size is stable or there is a significant trend of change, If there is a noticeable change in the trend of the activity there is a memory leak, we need to be specific analysis.


2. Using LOGCAT to detect memory leaks

When the garbage collector does a garbage collection, it makes a relative output in logcat, so we can also use this information to determine if there is a memory leak.

One, the first part of the above message produces the reason for the GC, a total of four types
Gc_concurrent when your heap memory is running out, this GC recycle is triggered.
Gc_for_malloc heap memory is full and trying to allocate new memory, so the system reclaims the memory
Gc_external_alloc before Android3.0 (Honeycomb), the release is generated by external memory (for example, before 2.3, the resulting bitmap object is stored in native memory). This type of memory allocation is no longer available in Android3.0 and later versions.
Gc_explicit call System.GC, in the middle is to click the Cause GC button to manually trigger the garbage collector generated log information

Two, freed 1413K means the GC freed up 1434K of memory

Three, 20% free 9349k/11644k, 20% represents the current proportion of allocated memory, 9349K represents the current active object occupied memory, 11644K represents the size of the heap

Four, paused 8ms + 3ms, Total 71ms, indicates the time that the GC app was paused and how long the GC spent

With these log information, we can know that the GC runs a few times after the successful release of some memory, if the allocated memory is continuously increasing, then there is obviously a memory leak, the following is a memory leak log information

It is clear that the ratio of free memory in the heap to the total heap is shrinking, and the memory occupied by the active objects in the heap is increasing.


Memory leak Analysis Combat

Here is a memory leak example code, which is a more common way of memory leakage, is to write some internal classes in activity, and these internal classes have a long life cycle phenomenon

Package Com.example.memoryleak;import Java.util.arraylist;import Java.util.list;import android.app.Activity;import Android.os.bundle;public class Leakactivity extends Activity {private list<string> List = new arraylist<string& gt; (); @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Simulate activity some other object for (int i=0; i<10000;i++) {List.add ("Memory leak!");} Turn on thread new MyThread (). Start ();} public class MyThread extends thread{@Overridepublic void Run () {super.run ();//analog time-consuming operation try {Thread.Sleep (ten *);} C Atch (interruptedexception e) {e.printstacktrace ();}}}}
Run the example code, select the Devices view, click the Updata heap tab above, then rotate the screen, repeat it several times, then click Dump HPROF file, and then Eclipse's Mat plugin will automatically open it for us, as


We see a histogram (histogram) below. He lists the statistics for each object, and the Dominator tree provides an arrangement of the most memory-occupying objects in the program, both of which I use most when troubleshooting memory leaks.

Histogram (histogram)

Let's take a look at histogram, mat one of the most useful tools that can list the number of instances of any class. It supports the use of regular expressions to find a particular class, and can also calculate the minimum or exact value of the reserved heap for all objects of that class, and we can enter leakactivity with regular expressions to see that histogram lists the classes associated with leakactivity


We can see that there are 16 objects in the Leakactivity, and the Mythread inner class, although there are so many objects leakactivity and mythread, but it is not possible to tell us exactly if there is a memory leak between the two objects. Select Com.example.memoryleak.LeakActivity, right-click, as


The Merge shortest Paths to GC Roots can see if an object is connected to the RC Roots with a reference chain, and in Java it is determined by accessibility (reachability analysis) that the object is alive. The basic idea of this algorithm is to use a series of "GC Roots" objects as the starting point, starting from these nodes to search down, the path of the search is called the reference chain, when an object to the GC Roots no reference chain connected, the object is judged to be recyclable objects, and vice versa cannot be recycled. We can choose Exclude all Phantom/weak/soft etc.references (to troubleshoot virtual references/weak references/soft references, etc.) because objects that are virtual references/weak references/Soft references can be recycled directly by GC.


You can see that leakactivity has a GC roots chain, that is, there is a memory leak problem, you can see Leakactivity was Mythread this$0 held.

In addition to using the merge shortest Paths to GC Roots we can also use

List object-with outgoing References Show selected objects holding those objects

List Object-with incoming References shows that the selected objects are held by those external objects

Show object by Class-with outgoing References shows which objects are held by the selected object, sorted by class

Show object by Class-with incoming References shows which external objects are held by the selected object, sorted by class


Dominator tree (dominating trees)

It can sort all objects according to the size of the heap, using the same method as the histogram (histogram), where I do not introduce too much


We know that in the example code above we know that the inner class will hold a reference to the external class, and if the life cycle of the inner class is too long, it will cause the external class memory to leak, then you ask, how should we write the problem that there is no memory leak? Since the inner class is not working, we can transfer the outer class weak reference if we need to use something inside the outer class or static inner class.

Package Com.example.memoryleak;import Java.lang.ref.weakreference;import Java.util.arraylist;import java.util.List Import Android.app.activity;import Android.os.bundle;public class Leakactivity extends Activity {private list< string> list = new arraylist<string> (), @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate);//Simulate activity some other object for (int i=0; i<10000;i++) {List.add ("Memory leak!");} Turn on thread new MyThread (this). Start ();} public static class MyThread extends Thread{private weakreference<leakactivity> mleakactivityref;public MyThread (leakactivity activity) {mleakactivityref = new weakreference<leakactivity> (activity);} @Overridepublic void Run () {super.run ();//analog time-consuming operation try {Thread.Sleep (ten *);} catch (Interruptedexception e) {E.prin Tstacktrace ();} If you need to use leakactivity, we need to add a judgment leakactivity activity = Mleakactivityref.get (); if (activity! = null) {//do Something}}} }

Similarly, Handler also has the same problem, such as the following code

Package Com.example.memoryleak;import Android.app.activity;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;public class Leakactivity extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); MyHandler handler = new MyHandler () handler.sendmessagedelayed (Message.obtain (), 10 * 60 * 1000); public class MyHandler extends handler{@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg);}}
We know that when using MyHandler to send messages, the message is added to the MessageQueue of the main thread, and the target of each message holds the MyHandler object, and MyHandler's this$ 0 will also hold the Leakactivity object, so when we rotate the screen, because each message is delayed for 10 minutes, it will inevitably lead to leakactivity leakage, so we need to change the code

package Com.example.memoryleak;import Java.lang.ref.weakreference;import Android.app.activity;import Android.os.Bundle; Import Android.os.handler;import Android.os.message;public class Leakactivity extends Activity {MyHandler handler;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); handler = new MyHandler (this); Handler.sendmessagedelayed (Message.obtain (), 10 * 60 * 1000); public static class MyHandler extends Handler{public weakreference<leakactivity> mleakactivityref;public MyHandler (leakactivity leakactivity) {mleakactivityref = new weakreference<leakactivity> (LeakActivity);} @Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); if (mleakactivityref.get () = null) {//do Something}}} @Overrideprotected void OnDestroy () {handler.removecallbacksandmessages (null); Super.ondestroy ();}} 

The above code ensures that the leakactivity is not compromised, and that we use handlerin the activity's Ondestory method. Removecallbacksandmessages(null), which ensures that the target myhandler of each message will be released when Leakactivity exits, So when using a non-static inner class, be aware that the inner class has a longer life cycle than the outer class, and if so, we can use the workaround above.


Common Memory leak issues

1. Both of the above scenarios

2. Resource objects are not closed, such as objects that have Cursor,io operations in a database operation

3. Call Unregisterreceiver () to cancel after calling Registerreceiver to register the broadcast

4. The view is called . Getviewtreeobserver(). Addonxxxlistener, without calling View.getviewtreeobserver(). Removexxxlistener

5.Android 3.0 ago, there is no use of the bitmap call Recycle (), of course, after Android 3.0 is not required, more detailed see http://blog.csdn.net/xiaanming/article/ details/41084843

6.Contenx leaks, such as the use of context objects in a singleton class, as follows

Import Android.content.context;public class Singleton {private Context context;private static Singleton Msingleton; Private Singleton (Context context) {This.context = context;} public static Singleton getinstance (context context) {if (Msingleton = = null) {synchronized (Singleton.class) {if ( Msingleton = = null) {Msingleton = new Singleton (context);}}} return Msingleton;}}

If we use Singleton.getinstance (this) or this instance in an activity, it will cause the activity to be referenced by the Singleton object. So this time we should use Getapplicationcontext() instead of the activity context,Getapplicationcontext() Gets the context is a global object, So this avoids a memory leak. Also, setting the context member to static can also cause a memory leak issue.

7. Do not rewrite the Finalize () method, we may sometimes release some resources before an object is recycled, possibly in the Finalize () method, but implement the Finalize object, and the process of creating and reclaiming is more time-consuming. When created, creates a new additional finalizer object that points to the newly created object. When recycled, at least two GC is required, the first GC detects that the object is only Finalizer referenced, put this object into finalizer.referencequeue at this time, because the Finalizer reference, the object can not be GC,
Finalizer$finalizerthread will constantly clean up the queue object, remove the current element, and execute the object's Finalize method, the cleanup object does not have any references, the next GC is recycled, so that the object survived longer, resulting in memory leaks.

If you have some memory leaks in the situation welcome to come, I am good update under!


Bloggers participated in the CSDN 2014 blog Star selection, I hope you have free to help vote on a vote, thank you!

Http://vote.blog.csdn.net/blogstar2014/details?username=xiaanming#content








Android performance optimization using the mat to analyze memory leak issues

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.