Android Memory leakage

Source: Internet
Author: User

 

Preface

 

Many people think that there should be no memory leakage due to the garbage collection mechanism of JAVA programs.

 

In fact, if we no longer use an object in a program, but because there are still references pointing to it, the garbage collector cannot recycle it. Of course, the memory occupied by this object cannot be used, this causes memory leakage. If we have been running java for a long time, and this memory leakage keeps occurring, the memory will not be available at the end. Of course, the memory leakage in java is different from that in C/C ++. If the java program ends completely, all its objects will be inaccessible, and the system will be able to recycle them. Its memory leakage is limited to its own, it does not affect the entire system. The memory leakage of C/C ++ is worse. Its memory leakage is a system level, even if the C/C ++ program exits, its leaked memory cannot be recycled by the system and will never be used unless the machine is restarted.

 

Memory leakage of an Android app has little impact on other apps. To ensure secure and fast running of Android applications, each Android application uses a proprietary Dalvik Virtual Machine instance to run. It is incubated by the Zygote service process, that is to say, each application runs in its own process. Android allocates different memory usage ceilings for different types of processes. If the program suffers a memory leak during running, the memory usage of the application process exceeds this limit, the system will regard it as a memory leak and kill it, which will kill only its own processes without affecting other processes (if there is a problem with system processes such as system_process, will cause the system to restart ).

 

1. Memory leakage caused by reference not released

 

1.1 Memory leakage caused by registration not canceled

 

This Android Memory leakage is more serious than pure java Memory leakage, because some other Android programs may reference the objects of our Anroid program (such as the registration mechanism ). Even though our Android program has ended, other reference programs still reference an object of our Android program, and the leaked memory cannot be recycled.

 

For example

 

Suppose we want to listen to the telephone service in the system in the LockScreen interface to obtain some information (such as signal strength), we can define a PhoneStateListener object in LockScreen, register it with the TelephonyManager service. For LockScreen objects, a LockScreen object is created when the screen lock interface needs to be displayed. When the screen lock interface disappears, the LockScreen object is released.

 

However, if you forget to cancel the previously registered PhoneStateListener object when releasing the LockScreen object, LockScreen cannot be reclaimed. If the screen lock interface is constantly displayed and disappears, a large number of LockScreen objects cannot be recycled, causing OutOfMemory and causing the system_process process to crash.

 

Although some system programs can automatically cancel registration (of course not timely), we should explicitly cancel registration in our program, when the program ends, all registration should be canceled.

 

Memory leakage caused by not clearing objects in the 1.2 collection

 

We usually add some object references to the collection. When we don't need this object, we didn't clear its references from the collection, so this set will become larger and larger. If the set is static, the situation is more serious.

 

Ii. Memory leakage caused by resource objects not being closed

 

Resource objects, such as Cursor and File files, usually use some buffer. When they are not used, they should be closed in time so that their buffer can be recycled in time. Their buffering not only exists in the Java virtual machine, but also exists outside the Java Virtual Machine. If we only set its reference to null without shutting them down, it will often cause memory leakage. Because there are some resource objects, such as SQLiteCursor (in the Destructor finalize (), if we didn't close it, it will call close () itself). If we didn't close it, the system also disables it when it is recycled, but this is too inefficient. Therefore, when the resource object is not used, it should call its close () function, close it, and then set it to null. make sure that our resource object is closed when our program exits.

 

The program usually queries the database, but it often does not close after using the Cursor. If our query result set is small, memory consumption is not easy to find. Memory problems can be reproduced only when a large number of operations are performed at a regular time, this will cause difficulties and risks for future testing and troubleshooting.

 

Iii. Some bad codes turn into memory pressure

 

Some codes do not cause memory leakage, but they, or do not effectively release unused memory in a timely manner, or do not effectively use existing objects, but frequently apply for new memory, this has a great impact on memory recovery and allocation. It is easy to force the virtual machine to allocate more memory to the application process, resulting in unnecessary memory expenses.

 

3.1 Bitmap does not call recycle ()

 

When a Bitmap object is not in use, we should call recycle () to release the memory before setting it to null.

 

Although recycle () is from the source code, calling it should immediately release the main memory of Bitmap, but the test results show that it does not immediately release the memory. However, I should be able to greatly accelerate the release of the main memory of Bitmap.

 

3.2 When constructing an Adapter, no cached convertView is used

 

Taking the BaseAdapter used to construct the ListView as an example, the methods in BaseAdapter are described as follows:

 

Public View getView (int position, View convertView, ViewGroup parent)

 

To provide ListView with the view object required by each item. Initially, the ListView will instantiate a certain number of view objects from the BaseAdapter based on the current screen layout, and the ListView will cache these view objects. When you scroll up the ListView, the view object originally located in the top list item will be recycled and then used to construct the bottom list item that appears. This construction process is completed by the getView () method, getView () the second View convertView parameter is the view object of the cached list item. (convertView is null if no view object is cached during initialization ).

 

It can be seen that if we do not use convertView, but re-instantiate a View object in getView () every time, it will waste time and cause memory garbage, increasing the garbage collection pressure, if garbage collection is too late, the virtual machine will have to allocate more memory to the application process, causing unnecessary memory consumption. You can view the process when ListView recycles the view object of list item:

 

Android. widget. AbsListView. java --> void addScrapView (View scrap) method.

 

Sample Code:

 

Public View getView (int position, View convertView, ViewGroup parent ){

 

View view = new Xxx (...);

 

......

 

Return view;

 

}

 

Corrected sample code:

 

Public View getView (int position, View convertView, ViewGroup parent ){

 

View view = null;

 

If (convertView! = Null ){

 

View = convertView;

 

Populate (view, getItem (position ));

 

...

 

} Else {

 

View = new Xxx (...);

 

...

 

}

 

Return view;

 

}

 

3.3 improper use of ThreadLocal

If we rudely set ThreadLocal to null without calling the remove () method or set (null) method, it may cause the ThreadLocal bound object to be recycled for a long time, thus producing Memory leakage.

For more information, see ThreadLocal Memory leakage.

 

From the column of robin

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.