Android GC Memory leakage

Source: Internet
Author: User

1. Android Memory leakage Concept

Many people think that JavaProgramBecause there is a garbage collection mechanism, there should be no memory leakage. 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 runs with a proprietary Dalvik Virtual Machine instance, 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 ).

Memory leakage example:

/*At this time, all object objects are not released because variable v references these objects. In fact, these objects are useless, but when referenced, GC is powerless (in fact, GC thinks it is still useful), which is the most important cause of Memory leakage.*/
Vector v =NewVector (10 );
For(IntI = 1; I <100; I ++ ){
Object o =NewObject ();
V. Add (O );
O =Null;
}

Apply for the object cyclically and put the applied object into a vector. If only the object itself is released, but the vector still references the object, therefore, this object cannot be recycled for GC. Therefore, if an object is added to a vector, it must be deleted from the vector. The simplest way is to set the vector object to null.

In general, the main cause of Memory leakage in memory management is the object reference that is retained but never used again.

2. Memory leakage

1) 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.

 

2) some poorCodeMemory 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.

A. 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.

B. when constructing the adapter, the cached convertview is not used

Taking the baseadapter used to construct the listview as an example, the methods in baseadapter are described as follows:

 
PublicView getview (IntPosition, 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.

Layout. xml

  <?  XML version = "1.0" encoding = "UTF-8"  ?>  
< Relativelayout Xmlns: Android = "Http://schemas.android.com/apk/res/android" Android: Orientation = "Vertical" Android: layout_width = "Fill_parent" Android: layout_height = "60dip" >
< Imageview Android: ID = "@ + ID/icon" Android: layout_width = "Wrap_content" Android: layout_height = "Wrap_content" Android: layout_alignparentleft = "True" Android: paddingleft = "9px" />
< Textview Android: ID = "@ + ID/text" Android: layout_width = "Wrap_content" Android: layout_height = "Wrap_content" Android: layout_torightof = "@ ID/icon" Android: textappearance = "? Android: ATTR/textappearancemedium" Android: paddingleft = "9px" />
</ Relativelayout >

Code that can cause memory leakage: badadapter. Java

Public ClassBadadapterExtendsBaseadapter {
 
......

@ Override
PublicView getview (IntPosition, view convertview, viewgroup parent ){
Log. D ("myadapter", "position:" + Position + "---"
+ String. valueof (system. currenttimemillis ()));
FinalLayoutinflater Inflater = (layoutinflater) mcontext
. Getsystemservice (context. layout_inflater_service );
View v = Inflater. Inflate (R. layout. list_item_icon_text,Null);
(Imageview) v. findviewbyid (R. Id. Icon). setimageresource (R. drawable. Icon );
(Textview) v. findviewbyid (R. Id. Text). settext (mdata [position]);
ReturnV;
}
}

CorrectionOptimization sample codeSample Code: goodadapter. Java

 Public   Class Goodadapter Extends Baseadapter {

......

@ Override
Public View getview ( Int Position, view convertview, viewgroup parent ){
Log. D ("myadapter", "position:" + Position + "---"
+ String. valueof (system. currenttimemillis ()));
Viewholder holder;
If (Convertview = Null ){
Final Layoutinflater Inflater = (layoutinflater) mcontext
. Getsystemservice (context. layout_inflater_service );
Convertview = Inflater. Inflate (R. layout. list_item_icon_text, Null );
Holder = New Viewholder ();
Holder. Icon = (imageview) convertview. findviewbyid (R. Id. Icon );
Holder. Text = (textview) convertview. findviewbyid (R. Id. Text );
Convertview. settag (holder );
} Else {
Holder = (viewholder) convertview. gettag ();
}
Holder. Icon. setimageresource (R. drawable. Icon );
Holder. Text. settext (mdata [position]);
Return Convertview;
}

Static Class Viewholder {
Imageview icon;
Textview text;
}
}

Mainactivity. Java

 Public   Class Mainactivity Extends Listactivity {
Private Badadapter/goodadapter madapter;

Private String [] marrdata;

/** Called when the activity is first created. */
@ Override
Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Marrdata = New String [1000];
For ( Int I = 0; I <1000; I ++ ){
Marrdata [I] = "Google Io adapter ";
}
Madapter = New Badadapter/goodadapter ( This , Marrdata );
Setlistadapter (madapter );
}
}

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.

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.