android--Memory Leak Check

Source: Internet
Author: User

Today on the subway saw a good memory leak simple Check the article, feel good yo, memory leaks is really a headache for every programmer, here to study a bit ^ ^

I. Common garbage collection Algorithms

See article

Reference Counting Method
The reference counting method is basically the simplest garbage collection strategy, and its core idea is:
When a pointer points to an instance, the count is added one, and when a pointer is deleted, the count is reduced by one, and when the count is 0 o'clock, the instance does not have a reference that can be reclaimed by the garbage collector.
The drawback of this recycling strategy is obvious:
1. Maintaining the reference count is a cost
2. Saving the count will consume extra space
3. Unable to process circular references

Mark Clear
Tag cleanup, as the name implies, is divided into 2 steps: 1. Mark 2. Clear. Tag cleanup scans all the unreachable objects from the root first, and unreachable objects are useless garbage objects. Then the collector clears the garbage objects centrally. The disadvantage of this strategy is: 1. The JVM is required to stop other work when labeling the collation 2. After finishing, a lot of memory fragments are generated.

Replication Algorithms
The core of the replication algorithm is to divide the memory space into two pieces, one at a time, to copy the surviving objects in the memory interval that is being used to another block at garbage collection, and then to clear all objects in the block being used, and then swap the roles between the two areas. Disadvantages:
1. Half of the internal passbook, low utilization

tag compression algorithm
The tag compression algorithm makes some improvements based on the markup cleanup algorithm, which compresses the valid memory together after marking all valid objects, and then clears the other areas.

split-generation algorithm
Because each algorithm has its own advantages, different recovery algorithms can significantly improve the efficiency of garbage collection according to the different characteristics of the object. The generational algorithm is based on this idea, like the one we introduced in the Java heap, usually the younger generation and the old age. The young generation is characterized by the short survival time of the object, so it is very appropriate to choose a replication algorithm at this time. While the objects in the old age are generally not recycled, it is obviously inappropriate to use a copy algorithm at this time, when the JVM chooses the tag compression algorithm.
For the younger generation and the old age, the average young generation of garbage collection frequency is very short, the old age of recovery frequency low-cost time. To cope with this situation, the JVM uses a data structure for the card table. It records whether an old age object in an area has a reference to a young generation object, and if it is not held, it does not need to scan the old age, which can increase the recovery efficiency of young generation.

Partitioning Algorithm
The generational algorithm divides the object into two parts according to the object's life cycle, and the partitioning algorithm divides the entire heap space into different regions, each of which is used independently and recycled independently. The advantage of this algorithm is that it can control the number of areas to be recycled, which can be used to reduce GC pauses by selecting the appropriate number of recoveries based on the target's pause time.

Two. The relationship between 4 types of references in Java and GC

See blog
Any object that is pointed to by a strong reference cannot be recycled;
Weak references must be recycled during GC;
Soft references are recycled only when the memory is low;
Virtual references can be recycled at any time, and the program can determine whether the object will be GC by judging whether the reference queue has been added to the virtual reference.

Consider the following three sets of examples:

public class Referencetest {
WeakReference W;

public void test() {    w = new WeakReference<String>(new String("aaa"));    System.gc();    try {        Thread.sleep(1000);    } catch (InterruptedException e) {        e.printStackTrace();    }    System.out.println(w.get());}

}
The answer is null, because the object "AAA" is only a weak reference to the W, which points to it.

String a = new string ("AAA");
w = new WeakReference (a);
System.GC ();
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (W.get ());
The answer is "AAA" because "AAA" is pointed to by a strong reference a, so the GC is not recycled, so W still has to get this object.

String a = new string ("AAA");
w = new WeakReference (a);
A = null;
System.GC ();
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println (W.get ());
The answer is NULL because "AAA" was initially pointed to by a strong reference, but then the strong reference was lost, so the GC "AAA" was recycled.

Three. Memory leaks

Although the garbage collector helps us kill most of the unused memory space, the garbage collector does not reclaim objects that are still referenced but are logically no longer being used. These objects accumulate in memory until the end of the program, which is what we call a "memory leak".
Here, let's make a difference. Memory jitter:
Memory jitter
In a very short period of time, allocating a lot of memory and then releasing it, this phenomenon can cause memory jitter. Typically, allocating large amounts of memory in the OnDraw method of the View control and freeing up large amounts of memory can easily cause memory jitter, resulting in degraded performance. Because a large amount of memory allocation and release in the OnDraw can put pressure on the system heap space, triggering GC work to free up more usable memory, while the GC is working, it eats valuable frame time (frame time is 16ms) and eventually leads to performance problems.

Q1: How does the memory leak occur in the Android development test?

For:
Method 1: Observe memory changes with repeated operations

Memory leaks are common for programs that consume more time and memory. We can determine whether there is a memory leak by repeatedly operating the application, such as repeatedly opening/closing the page, observing whether the memory changes are rising a little bit. Where do you see it?
1) You can view the heap in Ddms.

2) in Android Studio, you can view the Android monitor window

Note: Memory jitter and memory leaks differ for memory fluctuations:

Memory leaks We can usually use the MAT tool for professional analysis , which we'll explain later.
Method 2: Detect activity leaks through code using Leakcanary to detect
Leakcanary is an open-source library to check for memory leaks under Android. A good introduction to the article

If there is a tool that can automate these things, and even report a memory leak to you before an OOM happens, what a wonderful thing it is. Leakcanary is used to do this thing. If a memory leak occurs while testing your App, a notification will tell you on the status bar. Logcat will also have a corresponding log to inform you. Wow, that's cool! Since it is open source, let's look directly at how to use it.
1) Integrated Leakcanary library (in Android Studio)
Add dependencies in Studio, and with project structure, don't forget to set up Debugcompile and Releasecompile, which will end up with more of these lines of dependencies in Gradle.

{    debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.4‘    releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.4‘}

Reasons to set up Debug and Release editions:
On the debug version, integrate the Leakcanary library and perform memory leak monitoring, and on the release version, integrate a non-operational wrapper, which has no effect on program performance.
2) Initialize Leakcanary

    • We need to inherit application and call Leakcanary.install (this) in OnCreate (). Leakcanary.install () returns a well-configured Refwatcher instance.
 Public  class exampleapplication extends application {     Public StaticRefwatcherGetrefwatcher(Context context) {exampleapplication application = (exampleapplication) context.getapplicationcontext ();returnApplication.refwatcher; }PrivateRefwatcher Refwatcher;@Override  Public void onCreate() {Super. OnCreate (); Refwatcher = Leakcanary.install ( This); }}
    • Then, under Androidmanifest.xml registration.
 <application    android:name=".ExampleApplication "    android:allowBackup="true"    android:icon="@mipmap/ic_logo"    android:label="@string/app_name"    android:theme="@style/AppTheme">

3) Monitor activity leaks
We often use activity as a Context object, and the activity is referenced by various objects on different occasions. Therefore, Activity leaks are one of the important memory leaks that need to be checked. In application, we call Leakcanary.install (this). This method returns a well-configured Refwatcher instance. It also installs a activityrefwatcher to monitor Activity leaks. So, when we initialize, we can automatically monitor the activity leak, that is, when Activity.ondestroy () is called, if the activity is not destroyed, Logcat will print out a message telling you that a memory leak occurred. Leakcanary's first analysis may take a long time and wait patiently.

4) Monitor Fragment leakage

publicabstractclass BaseFragment extends Fragment {    @Override     publicvoidonDestroy() {        super.onDestroy();        RefWatcher refWatcher =     ExampleApplication.getRefWatcher(getActivity());        refWatcher.watch(this);    }}

When Fragment.ondestroy () is called, if the Fragment instance is not destroyed, the corresponding leak information is seen from the Logcat.

5) More
Leakcanary automatic detection of Activity leaks only supports Android ICS above version. Because Application.registeractivitylifecyclecallbacks () was introduced in API 14. If you want to monitor Activity leaks before ICS, you can overload the Activity.ondestroy () method, and then call Refwatcher.watch (this) in this method to implement it.

    • Take a look at the code.
      I created two activity, clicked the button in the first activity to enter Secondacitivity, created an anonymous inner class in Secondacitivity, and held a static variable, so congratulations, the memory leak is not far away from you. If you want to learn more about the possible memory leaks, check out the blogger's next blog post.
      Come on, on the code:
      Mainacitivy:
 Public  class mainactivity extends appcompatactivity {    Private inti = About;PrivateButton btn;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        BTN = (Button) Findviewbyid (R.id.button); Btn.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Intent Intent =NewIntent (Getapplicationcontext (), secondactivity.class);            StartActivity (Intent);    }        }); }}

Secondactivity:

 Public  class secondactivity extends Activity {    Private Static intindex =0;Private StaticObject inner;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.layout_second); Createinnerclass (); for(inti =0; I < +; i++) {//LOG.I ("DONGMJ", "Hello");index++; }    }voidCreateinnerclass () {class Innerclass {} inner =NewInnerclass (); }}

View the printed log

Obviously leakcanary prompted you to memory leaks, and has been accurate due to the secondasitivity in the inner class caused by, wow,, amazing.
Even more amazing is that the leaks app name appears in the mobile app, and when it opens, it shows the memory overflow time of your app, and you can click to view the details.

4 hprof File

In the above example, we found in log that the Hprof file was generated in the SD card, and you can analyze the memory leak based on this file.
How to export:

FileFile("heapdump.hprof");Debug.dumpHprofData(heapDumpFile.getAbsolutePath());

How to analyze Hprof files

This is a relatively big topic, interested in another open source library HAHA, its ancestors are MAT.

android--Memory Leak Check

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.