Mobile-side testing ===android memory leaks and GC mechanisms

Source: Internet
Author: User

This article transferred from: https://www.testwo.com/article/1153

1. Preface

Hello, small partners, I believe that you have encountered in the project test memory leaks, small series also really climbed a lot of pits. such as small part of the project, replaced the multi-instance version of the SDK, after the screen switch has Mapview not destroyed, resulting in memory leaks. Small series to test the watch project, because the watch memory is limited, often encountered in the test application is unresponsive or flash back, so small series of GC mechanism to learn further.

In this paper, the Android memory garbage collection mechanism is introduced, and then the analysis, location memory leak commonly used test methods to summarize, share to everyone.

2. Android Memory garbage collection (GC mechanism)

2.1 Reviews

the default for Android apps is three threads: "Main" main thread, GC thread, and heap thread , and during the GC thread run, the main thread will break execution. A difference between Java programs and native programs such as C + + is that Java virtual machines can automatically reclaim object instances that are no longer in use while running Java programs, thus avoiding the tedious work of programmers managing memory manually. If the device is a single-core CPU device, only one thread can be run at a time, so the main thread must be interrupted when the GC thread is running. But if there is a multi-core CPU on the device, that is, the main thread can run concurrently with the GC thread, in which case does the GC break the main thread? The answer is yes.

Although there are different implementations of the memory garbage collection algorithm, but some algorithms need to interrupt the execution of other Java threads, if the interruption time is too long, the user feels that the application's response speed is becoming more and more slow, and even may have a ANR error.

2.2Android Memory Management principles

2.2.1 Garbage Memory recovery algorithm

Common garbage collection algorithms reference counting, labeling and cleaning, copying, and recycling, where the Android system uses annotations and cleans up and copies the GC, not the generational recovery algorithm used in most JVM implementations. In many garbage collection implementations, it is often possible to see scenarios in which several algorithms are combined.

GC information in 2.2.2Logcat

The information format for GC output in Logcat is as follows:

Dalvik log information for virtual machines

In Davlik virtual machines (not art), each garbage collection returns a similar piece of information. Examples are as follows:

D/DALVIKVM (9050): Gc_concurrent freed2049k, 65% free 3571k/9991k, external 4703k/5261k, paused 2ms+2ms

They can be broadly divided into the following sections:

D/DALVIKVM: <GC_Reason> <amount_freed>,

[Reason for GC] [Total amount of recovered memory] [Statistical information on GC heap memory] [Statistics of external memory] [Interrupt Time]

The meanings of each field are as follows:

(1), GC for the reason, that is, the GC category, can be divided into:

    1. Gc_for_malloc indicates that the memory garbage collection process is caused by insufficient memory when allocating memory space such as (creating objects). The system kills the app's process and reclaims all memory.

    2. Gc_concurrent indicates that the GC is automatically triggered when memory usage reaches a certain cordon.

    3. GC_EXPLICIT indicates that the GC was triggered by an explicit request.

    4. Gc_external_alloc the garbage collection mechanism at the time of the API version (Android3.0). All memory in version 3.0 and above is allocated in the Dalvik heap. It is used to reclaim memory outside of the Dalvik virtual machine (for example, memory in bitmap or memory in Niobuffer).

    5. Gc_hprof_dump_heap this type of garbage collection is triggered when a HPROF file is requested to parse memory

(2) Total amount of memory recovered

(3) Statistical information of GC memory pairs after recovery

Percentage of free space in the heap and (number of objects in the heap)/(heap size)

(4), external memory statistics

System API version 10, Dalvik (Allocated memory)/(limited amount of memory) in a system that is below the virtual machine heap

(5), GC caused by the application of other threads interrupt Time

Concurrent types of garbage collection have two pause times: one at the beginning and the other at the end. The more content the heap, the longer the pause takes.

Observing the log information, if the number in the Heapstats (the number of objects in the heap)/(the size of the heap) is increasing, there is a high likelihood of a memory leak in the application.

(6), summary

Generally based on the following two clues to determine whether the application has a memory leak problem

1, the application runs for a period of time, because the internal throws Java.lang.OutOfMemoryError exception and crashes;

2, in the Logcat to see the frequent GC information;

3. Memory leaks

3.1 What is a memory leak

For different language platforms, the algorithm for tag-reclaim memory is not the same, like Android (Java) using Gc-root's tag-recycling algorithm. (The Google 2011 IO Conference) shows the recycling management strategy for Android memory.

Each circle node in the figure represents the memory resource of the object, and the arrows represent the accessible path. When the round node and GC roots exist to reach the path, it means that the current resource is being referenced and the virtual machine cannot be reclaimed (the yellow node in). Conversely, if the circle node and the GC roots do not exist, it means that the memory resources of the object are no longer referenced by the program, and the system virtual machine can be reclaimed during GC.

With the chestnut on top of memory recycling, then let's talk about a memory leak.

From the definition, the memory leak of the Android (Java) platform means that the unused object resource can be persisted with the Gc-root path, which prevents the system from being recycled. To give the simplest chestnut, we register a broadcast receiver in the activity's OnCreate function, but do not perform an anti-registration in the Ondestory function, and when the activity is finished, the activity object has gone through its own life cycle, Should be released by the resource recovery, but because there is no anti-registration, there is still a path between activity and gc-root exist, resulting in the activity is destroyed, but the memory resources can not be reclaimed.

3.2 the source of the leak

Here, return it to the following three categories:

(1). caused by self-coding

caused by the code of the project developer itself.

(2). Third-party code causes

The third-party code here consists of two categories: third-party non-open source SDK and open source third-party framework.

(3). System Reason

The problems caused by the Android system itself, such as WebView, Inputmethodmanager, and some third-party ROMs exist.

3.3 Positioning of the leak

Memory leaks are not like flash-back bugs, it is relatively difficult to troubleshoot, the more extreme situation is when the application of Oom to find that there is a memory leak problem, the user is too much impact. To do this, we hope to identify problems early in the testing process. Here are a few tools and methods to analyze memory leak issues.

3.3.1 Static Code analysis tool--lint

Lint is a tool that comes with Android studio, using a simple posture analyze-Inspect code and selecting the area you want to sweep.

Lint will make a warm note of the code that could cause the leak.

About lint, we can expand our own study.

3.3.2Android Memory Monitor

The tools provided by Android Studio are used to monitor the memory usage status of the application and are a very useful tool in development, which can be used to print out the state information of the memory.


The memory information obtained by printing is as follows, you can use the green triangle button in the upper right corner to analyze the leaked activity and some duplicate strings, currently only support these two, I hope Google can add more optional analysis rules.


3.3.3adb shell Command

Using adb shell Dumpsys meminfo [PackageName], you can print out the application memory information for the specified package name.


The use of this command can be very intuitive to observe the activity of the leakage problem, is a common analysis is commonly used in a way. In addition to using commands, Android Studio provides the following features, as well as using commands.

These are the tools and methods that I will use when I do the memory leak location analysis, which are often combined, and using multiple tools to analyze problems in a complementary way can improve our efficiency and ultimately achieve results.


The above, is a small series of memory leak analysis of some of the summary, if there are errors and deficiencies, also please point out. If you have a memory leak test, analysis, and what advice or experience, welcome to leave a message, discuss ~~o (∩_∩) o~~

Mobile End test ===android memory leak and GC mechanism (RPM)

Related Article

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.