Android Memory Leak Ultimate Solution Chapter (top) _android

Source: Internet
Author: User

I. Overview
In the development of Android, the word "memory leak" is often heard. "Memory Leak" is an object that no longer needs to be reused, but because other objects hold a reference to that object, its memory cannot be reclaimed. "Memory leak" slowly accumulate, will eventually lead to Oom, sink, destroyed in the nest. So in the process of writing code, should pay attention to avoid will lead to "Memory leak" code, improve the robustness of the software.
This paper will solve the problem of "memory leak" from three angles of discovering problems, solving problems and summarizing problems.

Second, the Memory leak inspection tool heap

工欲善其事 its prerequisite, to detect "memory leaks", you need to use the heap tools and mat tools in Ddms to roughly analyze the existence of a "memory leak," and the heap tool to analyze where "memory leaks" occur.

Introduction to the use of heap tools

Specific operations

    • 1. In the list of devices devices, locate your device and click the process you want to monitor.
    • 2. Click the "Update Heap" button to update the heap memory.
    • 3. Click the "Heap" view to view the memory.
    • 4. Each time the activity is withdrawn and entered, click on "Cause GC" to manually invoke the GC to release the applied memory.
    • 5. Observe the line of data oject, each time clicking "Casue GC", observe the value of total size, if the value is increasing, then the application has a "memory leak."

Let's simulate a memory leak and then use the heap tool to determine if there is a memory leak.
The previous paragraph has a memory leak code:

public class Leakaty extends activity {

 @Override
 protected void onCreate (Bundle savedinstancestate) {
  Super.oncreate (savedinstancestate);
  Setcontentview (r.layout.aty_leak);
  Testleak ();

 }

 /**
  * Test memory leak code/
 private void Testleak () {
  new Thread (new Runnable () {

   @Override
   public void Run () {while
    (true) {
     try {
      thread.sleep (1000);
     } catch (Interruptedexception e) {
      E.printstacktrace ();}}}
  ). Start ();
 }

The above code has a memory leak, the new Runnable () {} is a non-static anonymous inner class, so it will strongly refer to the outer object to create it leakaty, we test the memory leak process, turn on the mobile phone in the direction of rotation function, constantly rotating the phone, Let Leakaty constantly create new instances. Theoretically, if there is no such leaking code, the previous activity will be reclaimed after ondestory the memory. And once the leaked code is present, the newly created Ruannale instance will always be running, it will not be reclaimed, and its strongly referenced leakaty will not be reclaimed, so the leakaty that is created before the screen is constantly rotated will not be released, causing the rotation n times, and the presence of N in memory + 1 Leakaty instances.
The first time the heap tool presses the screenshot of the cause GC button:


The total size of the data object in the above figure is 1.031M. After several rotating screens, let's take a look at the screenshot


Total size changed to 2.059M, from 1.031M to 2.059M, every time the GC is called the sum of data object does not fall back, so you can verify that the above code is really a memory leak problem, then where is the leak occurred? The answers can be analyzed by means of mat tools.

Three, memory leak analysis tool mat

To pass mat analysis, you need to provide a. hprof file. We can dump the current heap memory information through the Dump HPROF file button. We'll save it as 1.hprof.

The exported 1.hprof format needs to be passed ... The Hprof-conv.exe tool in the \sdk\tools\ directory is converted to be mat successfully imported, we convert it to out1.hprof

Import Out1.hprof into the Mat tool, File->open Heap Dump ...

Click on the tab on the left Overview,actions->histogram

In the histogram interface, because we want to know if the activity is leaking, enter the keyword activity and press ENTER.

Then you can get the relevant search results for the activity, and there are 7 instances of activity in the search results shown below. Click to select the Red box where the icon, right-click->merge shortest Paths to GC roots->exclude all phantom/weak/soft etc. references. Excludes virtual references, weak references, soft reference instances, and the rest are strong reference instances.

From the filtered list of strong references, we can see that all seven instances are referenced by thread. So verify that the above code does have a memory leak.

Iv. Summary of this article

Memory leak detection can use the heap tool, and memory analysis can use the Mat tool. In the case of this article, a memory leak is mentioned, that is, the object of the non-static inner class will strongly reference its outer object, and once the instance of the non-static inner class is not released, its outer object will not be released, so it will cause a memory leak. The next article will discuss specifically, in the Android development process, which writing is likely to cause memory leaks, how to solve? Please read the Android memory Leak Ultimate Solution (below).

The above is the entire content of this article, I hope you like.

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.