An android application memory leak describes the difference between a memory leak and a memory overflow
memory Overflow (out of Memories) is when the program is requesting memory, there is not enough memory space for its use, and an out of memories appears. For example, in each of our Android programs at run time the system will allocate a certain amount of memory space, when the program is running in the memory required to exceed this limit will be reported memory overflow (out of memories).
memory leak refers to a program that cannot release the requested memory space after it has requested memory. Multiple memory cannot be freed, and the memory that is consumed by the program is incremented until the memory limit of the system is exceeded to report a memory overflow.
Why there is a memory leak in Java
When you are learning Java, when reading related books, the first thing about Java is that Java uses GC to automatically manage the recovery of memory, and programmers do not need to call functions to free memory. Therefore, many people think that Java does not have a memory leak problem, the real situation is not so, especially when we develop mobile phones and tablet-related applications, often due to the accumulation of memory leaks quickly caused the program to crash. To understand this, we need to first understand how Java manages memory.
memory Management in Java
Java memory Management is the problem of object allocation and release, in Java, programmers need to pass the keywordNewRequest memory space for each object (except the base type), and all objects allocate space in the heap. In addition, the release of the object is determined and executed by the GC. In Java, the allocation of memory is done by the program, and the release of memory is done by the GC. The two lines of revenue and expenditure are indeed simplifying the programmer's work. But it also adds to the burden on the JVM. This is one of the reasons why Java is running slower. Because, in order for the GC to properly release each object, the GC must monitor the running state of each object, including the object's request, reference, and reference, and the assignment GC needs to be monitored.
The object's state is monitored to release the object more accurately and in a timely manner, and the fundamental principle of releasing the object is that the object is no longer referenced.
To better understand how the GC works, we can consider the object as a vertex of the directed graph, consider the reference relationship as a directed edge of the graph, and have a directed edge from the referrer to the cited object. In addition, each thread object can be used as the starting vertex of a graph, for example, when most programs are executed from the main process, the graph is a root tree that starts with the main process vertex. In this graph, the object that the root vertex can reach is a valid object, and the GC will not reclaim those objects. If an object (connected sub-graph) and this root vertex are unreachable (note that the graph is a forward graph), then we think that this (these) objects are no longer referenced and can be recycled by GC.
Below, let's give an example of how memory management is represented by a graph. For every moment of the program, we have a graph of graphs that represent the memory allocations of the JVM. On the right, the left program runs to line 6th.
Java uses a graph-like approach to memory management, which eliminates the problem of reference loops, such as having three objects and referencing each other, so that GC can reclaim them as long as they are unreachable from the root process. The advantage of this approach is that the precision of managing memory is high, but the efficiency is low. Another common memory management technique is the use of counters, such as the COM model, which uses counter-mode management artifacts, which are low-precision rows (difficult to handle circular references) compared to a forward graph, but perform efficiently.
memory leaks in Java
Below, we can describe what a memory leak is. In Java, the memory leak is the existence of some assigned objects, these objects have the following two characteristics, first of all, these objects are accessible, that is, in the graph, the existence of the path can be connected to it, and secondly, these objects are useless, that is, the program will no longer use these objects. If the object satisfies both conditions, these objects can be judged as a memory leak in Java, which is not reclaimed by the GC, but it consumes memory.
In C + +, memory leaks are larger in scope. Some objects are allocated memory space, and then unreachable, because there is no GC in C + +, the memory will never be returned. In Java, these unreachable objects are collected by the GC, so programmers do not need to consider this part of the memory leak.
Through the analysis, we learned that for C + +, programmers need to manage their own edges and vertices, and for Java programmers only need to manage the edge (do not need to manage the release of vertices). In this way, Java improves the efficiency of programming.
So, with the above analysis, we know that there is also a memory leak in Java, but the scope is smaller than C + +. Because Java is guaranteed by the language that any object is accessible, all unreachable objects are managed by the GC.
For programmers, GC is basically transparent and invisible. Although we have only a few functions that can access the GC, such as the function System.GC (), which runs the GC, the function does not guarantee that the JVM's garbage collector will execute, as defined by the Java language Specification. Because different JVM implementations may use different algorithms to manage the GC. Typically, a GC's thread has a lower priority level. There are a number of policies that the JVM calls the GC, some of which are used to a certain extent, the GC starts to work, there are timed executions, there is a gentle execution of the GC, and some interrupt-execution GC. But generally speaking, we don't need to care about this. Unless the GC's execution affects the performance of the application on certain occasions, such as a web-based real-time system, such as a network game, where the user does not want the GC to suddenly interrupt application execution for garbage collection, then we need to adjust the GC's parameters so that the GC can free up memory in a gentle manner. For example, by decomposing garbage collection into a series of small steps, the sun-provided hotspot JVM supports this feature.
Android Memory leak summary
When we develop the Android program, often encounter memory overflow situation, in our launcher development process, there is a memory leak problem. The following combined with our actual problems encountered in the development of launcher, share a memory leak how to solve.
Common memory leaks in Android
-
Collection class leaks
The collection class if there are only methods to add elements, and there is no corresponding removal mechanism, the memory is occupied. If the collection class is a global variable (such as a static attribute in a class, a global map, etc., there is a static reference), then there is no corresponding deletion mechanism, which is likely to cause the collection to consume only a few more memory. Take a look at the example code below, and it's easy to see that, for example, we all like to do some caching through HashMap, and that's a lot to keep in mind.
new ArrayList(); for (int1100; i++) { ObjectnewObject(); v.add(o); null; }
In the above code, list is a global variable, it is useless to empty the object's reference only after it, because the object is held by the list and is not recycled by GC in the absence of the end of this class life cycle.
public Class AppManager {private static Appman Ager instance; private Context context; private appmanager (Context context) {this . Context = context; } public static appmanager getinstance (Context context) {if (Instance = = null ) {instance = new AppManager (context); } return instance; } }
In the above example, if the context being passed in is Activity,appmanager is a static variable, its life cycle and application are the same. Since the activity has been held by the instance, the activity cannot be recycled. A memory leak will occur. Workaround: You can pass in application here, because the life cycle of application is from start to finish.
- Non-static inner class creates a memory leak caused by a static instance
The non-static inner class holds the class by default, and if its instance is static in this class, it means that its life cycle is as long as application. Then a static instance of the default non-static inner class holds the class, and the resource is not taken out of the GC, causing a memory leak.
public class MainActivity extends Activity{ private static LeakInstance mLeakInstance; @override public void onCreate(Bundle onsaveInstance){ ...... } class LeakInstance{ ..... }}
In the code snippet above, Leakinstance is an inner class in activity that has a static instance mleakinstance that has the same life cycle as application, and that it holds the mainactivity by default. This causes the activity not to be dropped by GC, causing a memory leak.
An anonymous inner class runs on an asynchronous thread.
The anonymous inner class holds a reference to its class by default, and if the anonymous inner class is placed in a thread to run, and the life cycle of the thread is not the same as the life cycle of the class, it will cause the class to be held by the thread and cannot be freed. Causes a memory leak. Take a look at the following sample code:
public class MainActiviy extends Activity{ private Therad mThread = null; private Runnable myRunnable = new Runnable{ public void run{ ...... } } protected void onCreate(Bundle onSaveInstance){ ....... mThread = new Thread(myRunnable); mThread.start(); }}
In the example above myrunnable holds the Mainactiviy,mthread life cycle and the activity is not the same, Mainactiviy will be held until the thread runs to the end. Causes a memory leak.
- Memory leaks caused by Handler
The memory leak caused by the use of Handler should be said to be the most common, many times we want to avoid the ANR and not the main thread time-consuming operation, in the processing of network tasks or encapsulation of some request callback and other APIs with the help of Handler, but Handler is not omnipotent, for Handler's use of code to write an irregular specification is likely to cause a memory leak. Also, we know that Handler, message, and MessageQueue are all interrelated, in case the message sent by Handler has not been processed, then the message and the Handler object that sent it will be threaded Messagequeu E has been held.
Because Handler belongs to the TLS (Thread Local Storage) variable, the life cycle and Activity are inconsistent. Therefore, this implementation is generally difficult to ensure that the life cycle of the View or Activity is consistent, it is easy to cause the failure to release correctly. You can look at the following:
public MainActivity extends Activity{ private Handler mHandler = new Handler(); protected void onCreate(Bundle onSaveInstance){ ....... mHandler.postDelay(new Runnable(){ },1000*1000); }}
In the code above, mhandler the delay for a long time, actually holding the mainactivity, if the activity died, then he can not be recycled. Need to wait for Mhandlder to release the held resources.
How to discover memory leaks mat
1. Directly by observing the memory of Android monitor intuitive observation, for example, when we develop launcher, launcher activity in the screen switching between the time of the case of a leak, when the value will continue to grow, And the memory cannot be freed by manually tapping the GC.
Or you can observe it in DDMS.
2. Find through the Mat tool
There are a lot of analysis tools for Java memory leaks, but it is well known that the number of mats (memory analysis tools) and Yourkit.
Mat analyzes the total memory footprint of the heap to determine if there is a leak
Open the DDMS tool, select the "Update Heap" icon on the left Devices view page, then switch to the heap view on the right, and click the "Cause GC" button in the heap view, so that the process that needs to be detected can be monitored.
In the middle of the heap view, there is a type called data object, which is an object of the class type that exists in our program. In the data object row, there is a column "total size", whose value is the amount of memory for all Java data Objects in the current process, in general, the size of this value determines whether there is a memory leak. It can be judged as follows:
Enter an application, continue to operate the application, while observing the data object's total size value, under normal circumstances the total size value will be stable in a limited range, that is, because the code in the program is good, there is no object is not garbage collection situation.
Therefore, although our continuous operation will continue to generate many objects, and in the process of the virtual machine continuous GC, these objects are recycled, memory consumption will fall to a stable level; Conversely, if there is no object reference in the code, then the total of the data object The size value does not come down significantly after each GC. As the number of operations increases, the value of total size becomes larger and higher until an upper limit is reached, causing the process to be killed.
Mat Analysis Hprof to locate memory leaks
This is an effective means of using mat to locate problems after a memory leak occurs.
A) Dump out memory leaks the memory image hprof, analyzing the class of suspected leaks:
B) Analyze external objects that hold references to such objects
C) Analyze the GC path of these objects that hold the reference
D) Analyze the GC path of each object individually
From this path it can be seen that a Antiradiationutil tool class object holding a mainactivity reference causes Mainactivity to fail to release. At this point it is necessary to enter the code analysis at this time Antiradiationutil reference holding is reasonable (if Antiradiationutil held a mainactivity context causes the program to exit Mainactivity can not be destroyed, That is usually a memory leak).
Mat to locate the root cause of the memory leak by comparing the hprof before and after the operation
To find a memory leak, you typically need two dump results for comparison, open the Navigator history panel, and add histogram results from two tables to Compare basket
A) The first hprof file (Usingfile > Open Heap Dump).
B) Open histogram view.
C) in Navigationhistory view (if you don't see it from window >show view>mat-navigation history), right-click Histogram and select Add to Compare Baske T.
D) Open a second hprof file and redo steps 2 and 3.
E) switch to compare basket view, then click Compare the Results (the red "!" in the upper right corner of the view!) icon).
F) Analysis of comparison results
You can see the data object comparison results of two hprof.
In this way, you can quickly locate the object increment held before and after the operation, further locating the actual cause of the memory leak caused by the current operation is what data object was compromised.
Attention:
If the dump file obtained with the Mat Eclipse plugin is not required to be converted, it can be opened in the mat, and ADT will automatically convert.
and the Mobile SDK Dump file to be converted to be mat recognition, the Android SDK provides this tool Hprof-conv (located under Sdk/tools)
First, go to your Android SDK Tools directory via the console to execute the following command:
./hprof-conv Xxx-a.hprof Xxx-b.hprof
For example Hprof-conv input.hprof out.hprof
You can now open the out.hprof in the eclipse's mat.
The following will introduce you to a Dick fried day tool –leakcanary.
Leakcanary
What is Leakcanary? Why choose it to detect an Android memory leak?
Don't worry, let me slowly tell you!
Leakcanary is an open source class library developed by a great god pierre-yves Ricau in foreign countries to detect memory leaks. In general, in PvP memory leaks, we will go through the following key steps:
1, understand outofmemoryerror situation.
2, reproduce the problem.
3, in the event of memory leaks, the memory dump out.
4, in the event of memory leaks, the memory dump out.
5. Calculate the shortest strong reference path of this object to GC roots.
6. Determine which reference in the reference path is not available, and then fix the problem.
It's complicated, right?
If you have a class library that can get all of these things done before the OOM happens, then you just have to fix the problems. That's what Leakcanary did. You can easily detect memory leaks in the debug package.
Take a look at this example (excerpt from the leakcanary Chinese instructions, all links to reference documents are attached below):
class Cat{}class Box{ Cat hiddenCat;}class Docker { //静态变量,生命周期和Classload一样。 static Box cainter;} // 薛定谔之猫Cat schrodingerCat = new Cat();box.hiddenCat = schrodingerCat;Docker.container = box;
Create a Refwatcher to monitor object references.
// 我们期待薛定谔之猫很快就会消失(或者不消失),我们监控一下refWatcher.watch(schrodingerCat);
When a memory leak is found, you will see a very nice leak trace report:
GC ROOT Static Docker.container
References Box.hiddencat
Leaks Cat Instance
We know that you are very busy and have a lot of needs every day. So we make this very simple, you just need to add a line of code. Then the leakcanary will automatically detect the activity's memory leaks.
public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); }}
Then you'll see a nice interface in the notification bar:
A very straightforward way to expose memory leaks in front of us.
Demo
A very simple leakcanary demo: A very simple leakcanary Demo:https://github.com/liaohuqiu/leakcanary-demo
Access
Add references in Build.gradle, different compilations use different references:
dependencies { debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.3‘ releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3‘ }
How to use
Use Refwatcher to monitor those objects that should be recycled.
RefWatcher refWatcher = {...};// 监控refWatcher.watch(schrodingerCat);
Leakcanary.install () returns a predefined Refwatcher, and also enables a activityrefwatcher to automatically monitor the Activity that was leaked after the call to Activity.ondestroy ().
To configure in application:
public class ExampleApplication extends Application { public static RefWatcher getRefWatcher(Context context) { ExampleApplication application = (ExampleApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); refWatcher = LeakCanary.install(this); }}
Use Refwatcher to monitor Fragment:
public abstract class BaseFragment extends Fragment { @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity()); refWatcher.watch(this); }}
Monitor Activity with Refwatcher:
public class Mainactivity extends Appcompatactivity {
... @Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Add the following two lines of code to the initial activity of your application Refwatcher Refwatcher = Exampleapplication.getrefwatcher (this); Refwatcher.watch (this); TextView = (TextView) Findviewbyid (r.id.tv); Textview.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) { StartAsyncTask (); } });} private void Async () {StartAsyncTask ();} private void StartAsyncTask () {//This async task was an anonymous class and therefore have a hidden reference to the OU ter//Class mainactivity. If the activity gets destroyed before the task finishes (e.g. rotation),//The activity instance would leak. New asynctask<void, Void, void> () {@Override protected void doinbackground (void ... params) { Do some slow work in background systemclock.sleep (20000); return null; }}.execute ();}
}
Working mechanism
1.refwatcher.watch () creates a keyedweakreference to the object to be monitored.
2. Then check whether the reference is cleared in the background thread, and if not, call the GC.
3. If the reference is not cleared, dump the heap memory into a. hprof file in the file system corresponding to the APP.
4. In another process, Heapanalyzerservice has a heapanalyzer that parses the file using haha.
5. Thanks to the unique reference key, Heapanalyzer locate the keyedweakreference and locate the memory leak.
6.HeapAnalyzer calculates the shortest strong reference path to the GC roots and determines whether it is a leak. If so, establish a chain of references that leads to leaks.
7. The reference chain is passed to the Displayleakservice in the APP process and is displayed in the form of a notification.
OK, this is no longer in-depth, want to know more on the author GitHub homepage.
Androidstudio Self-analysis tool
Using the memory tool that comes with Android Monitor, click GC First, and then generate the Hprof file as shown in the figure.
Then open double-click the generated file
You can see the cause of the memory leak in a quick look.
A memory overflow in the
The following demonstrates a specific case of a memory leak
Create a new project in Android Studio and create a new singleton class for AppManager:
publicclass AppManager { privatestatic Context sContext; privatestatic AppManager instance; public staticgetInstance(Context context){ if(instance==null){ new AppManager(context); } return instance; } privateAppManager(Context context){ sContext = context; }}
In the code snippet above, the context is written as a static variable in the class. Keep looking at the following code:
protected void OnCreate (Bundle savedinstancestate) {Super. OnCreate(savedinstancestate);Setcontentview (R. Layout. Activity_main);Toolbar Toolbar = (Toolbar) Findviewbyid (R. ID. Toolbar);Setsupportactionbar (Toolbar);Floatingactionbutton fab = (Floatingactionbutton) Findviewbyid (R. ID. Fab);Fab. Setonclicklistener(New View. Onclicklistener() {@Override public void OnClick (view view) {Snackbar. make(View,"Replace with your own action", Snackbar. LENGTH_long). Setaction("Action", null). Show();} });AppManager. getinstance(this);}
This time we call the screen a few times, then found
We usually use this class in the activity as in the example code above. Let's call the mat analysis tool to parse the above code:
The first step:
Run the above code, after the screen several times, click.
Often, when you do this, you generate
This is where you convert the generated hprof file into a standard hprof file and then open it with a mat.
And then you open it with a mat.
Click Histogram we can see the input we suspect the leak object, "activity"
We can see that there are two instances in our mainactivity, suspect that one of the two has been leaked, continue down the analysis, right-click to select the list incoming object
You can refer to this two activity information.
It is clear that one of our activity is held by Scontext, Scontext is static, its life cycle is the same as the life cycle of application, so the activity is leaked throughout the application life cycle.
Reference Documentation:
Ibm:java memory leaks
Leakcanery:leakcanery Chinese User manual
Mat:mat Using Tutorials
Introduction to Android application memory leaks