Deep Android Memory leaks

Source: Internet
Author: User

Deep memory leaks

Memory leaks in Android apps are actually a heap memory leak for Java virtual machines .

1. Knowledge Reserve 1. Java memory model


Related Memory object model, refer to blog explaining Java memory model

1) Register (register). This is the fastest save area, which is mainly because it is located inside the processor . However, the number of registers is very limited, so the register needs to be allocated by the compiler. we have no direct control over this, nor can we find any trace of the register in our own program.

(2) stacks (stack). 在执行函数(方法)时,函数一些内部变量的存储都可以放在栈上面创建,函数执行结束的时候这些存储单元就会自动被释放掉。 located in Universal RAM (random access memory). Direct support for processing is available through its "stack pointer". If the stack pointer moves down, the new memory is created, and if you move up, the memory is freed. This is a particularly fast, particularly effective way to save data, second only to registers.

(3) heaps (heap). A universal memory pool (also in the Ram area), the heap is a discontinuous memory area, the heap space is more flexible and particularly large . The Java object is saved (the member variable inside the object is also in it). It takes longer to allocate storage space in the heap! Also called dynamic memory allocation.

(4) static storage (storage). "Static" here means "in a fixed position" (albeit also in RAM). During the run of the program, the data that is stored statically is always waiting to be called. The static keyword can be used to indicate that a particular element of an object is static. However, the Java object itself will never be placed in a static storage space, ending with the end of the life cycle of the JVM, which is released when the app exits completely .

(5) constant storage (constant storage). The constant value is usually placed directly inside the program code. It is safe to do so, because they will never change.

(6) non-RAM storage (Non-storage-ram). If the data is completely independent of a program, the program can still exist when it is not running and outside the control of the program. The two most important examples are "streaming objects" and "fixed objects". For streaming objects, the object becomes a byte stream, which is usually sent to another machine. For fixed objects, objects are saved on disk.

2.GC recovery mechanism

Reference from http://blog.csdn.net/jiafu1115/article/details/7024323

First, the JVM recycles the heap.

Classification in 1.JVM heap
(1) 新域young generation:存储所有新成生的对象(2) 旧域old generation:新域中的对象,经过了一定次数的GC循环后,被移入旧域(3) 永久域PermanentGeneration:存储类和方法对象,从配置的角度看,这个域是独立的,不包括在JVM堆内。默认为4M。
2.GC Recycling Process
1.当eden满了,触发young GC;2.young GC做2件事:一,去掉一部分没用的object;二,把老的还被引用的object发到survior里面,等下几次GC以后,survivor再放到old里面。3.当old满了,触发full GC。full GC很消耗内存,把old,young里面大部分垃圾回收掉。这个时候用户线程都会被block。
3.Gc Recycling Summary
1.JVM堆的大小决定了GC的运行时间。如果JVM堆的大小超过一定的限度,那么GC的运行时间会很长。2.对象生存的时间越长,GC需要的回收时间也越长,影响了回收速度。3.大多数对象都是短命的,所以,如果能让这些对象的生存期在GC的一次运行周期内,wonderful!4.应用程序中,建立与释放对象的速度决定了垃圾收集的频率。5.如果GC一次运行周期超过3-5秒,这会很影响应用程序的运行,如果可以,应该减少JVM堆的大小了。6.前辈经验之谈:通常情况下,JVM堆的大小应为物理内存的80%。
3. Memory Jitter

The term memory jitter can be used to describe 在极短时间内分配给对象的过程 .

For example, when you configure a series of temporary objects in a looping statement, or when you configure a large number of objects in the drawing function, which is equivalent to an inner loop, you need a frame to use these features when the screen needs to be redrawn or animated, but it will quickly increase the pressure on your heap.

Memory Monitor RAM jitter legend:

2. The impact of memory leaks on programs 1. Direct: consumes memory, resulting in the system application itself of insufficient memory outofmemory.

An Android application, in fact, is a JVM virtual machine instance, and a JVM instance, at the initial time, the size of different 16m,32m,64m (depending on the phone manufacturer and version of the different), of course, size can also be modified, reference to modify the blog.

2. Indirect: GC Recycling frequently results in application stuttering ANR.


First, when memory is low, the GC proactively reclaims unused memory. However, memory recycling also takes time.

, when Android is drawing (playing video, etc.), draw to the interface object, and GC recycle garbage resources between the high frequency alternating execution. Memory jitter is generated.

A lot of data will contaminate the memory heap, and there will be a lot of GCs to start, and as a result of this extra 内存压力 , there will be a sudden增加的运算造成卡顿现象

Any action on any thread will need to be paused, waiting for the GC operation to complete before other operations can continue 所以垃圾回收运行的次数越少,对性能的影响就越少 .

3. Causes of memory leaks

The nature of memory leaks: objects that are no longer used, are incorrectly referenced, and cannot be recycled

Unreferenced objects can be reclaimed by the garbage collection mechanism, and referenced objects cannot be reclaimed by the garbage collection mechanism.
GC reclaims garbage memory when memory is low
Garbage memory is a memory that no one else uses, good memory

A memory leak is a memory that is being used by someone else, not a garbage memory

Heap reference memory leak (heap leak)
 1.静态变量持有 已经没有用的对象,导致对象无法被回收.例如静态集合类引起内存泄露 2.单例中持有的引用,当activity重新构建后,单例持有的是上一个activity实例.导致上一个无法被回收. 3.事件监听器和回调.如果一个类注册了监听器,但当该类不再被使用后没有注销监听器,可能会发生内存泄漏。 4.静态内部类,持有 对象. 5.Handler 内存泄漏
System resource Leaks (Resource Leak)

Mainly refers to the program using the system allocation of resources such as bitmap,handle, socket and so does not use the corresponding function to release, resulting in system resources waste, serious can lead to lower system performance, system operation is not stable. This type of memory leak can be avoided by creating a connection in the try code block and releasing the connection in finally.

4. Memory Leak analysis Tool

There are several tools in Android studio for Memory leak optimization analysis (Eclipse has similar tools).

1.Memory Monitor Memory Monitor.

2.Dump Java Heap

3.Android Device Monitor (Eclipse series Tools Class)

4. Third-party library Leakcanary (extremely simple)

Leakcanary's GitHub Address

5. Instance solutions for memory leaks

instead of resolving memory leaks, it is more about avoiding memory leaks. Because once a memory leak occurs, the memory restarts, even if the JVM needs to be restarted, that is, restarting the application. Even if it does, it can't be solved.

1. Memory leaks due to changes in collection objects
//In this example, because the property value of the Object S2 has been changed,//So it cannot be removed from the set, so the S2 reference is maintained in the set .//cannot be recycled, causing a memory leak. Set<student> set =NewHashset<student> (); Student S1 =NewStudent ("Jack"); Student s2 =NewStudent ("Mary"); Student s3 =NewStudent ("Eason");    Set.add (S1);    Set.add (S2);    Set.add (S3); System.out.println (Set.size ());//3S2.setname ("Jackson");//Modify the property, at which point the hashcode value of the S2 element has changedSet.remove (S2);//Remove does not drop, causing a memory leakSet.add (S2);//Add SuccessSystem.out.println (Set.size ());//4
2. Memory leaks caused by singleton
/** * Created by CCJ on 2016/11/3. * * Public  class singleexample {    Private StaticSingleexample mexample;PrivateContext context;Private Singleexample(Context context) { This. Context = Context; }/** * When Mainactivity is destroyed and rebuilt, the context at this time will not walk if (mexample = = null), but return directly.     * This context is still the context of the previous activity instance, so the last activity instance was not released, causing a memory leak * * At this point, only the context of the application should be used as a contextual solution. * @param context * @return  * *     Public StaticSingleexamplegetexampleinstance(Context context) {if(Mexample = =NULL) {mexample =NewSingleexample (context); }returnMexample; }}
3. Memory leaks caused by anonymous internal classes
//android开发经常会继承实现Activity/Fragment/View,此时如果你使用了匿名类,并被异步线程//持有了,那要小心了,如果没有任何措施这样一定会导致泄露     publicclass MainActivity extends Activity {        new Runnable() {            @Override            publicvoidrun() {            //异步代码            }        };    }
Memory leaks due to 4.Handler

Java refers to the classification of strong reference, SoftReference, WeakReference, phatomreference four kinds.

In the development of Android application, in order to prevent memory overflow, we can apply soft reference and weak reference technique when dealing with some objects that occupy large memory and have long declaration period.

A soft/weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it. This queue allows you to know the list of objects that have been reclaimed by soft/weak references, thereby clearing the failed soft/weak references for the buffer.

/*: Avoid using non-static inner classes in Activity, such as above, where we declare Handler as static, its survival is irrelevant to the life cycle of the activity. It is also recommended to use static inner class + WeakReference to introduce activity in a weak reference and avoid direct activity as a context. Pay attention to empty before each use * * Public  class sampleactivity extends Activity {    Private FinalHandler Mleakyhandler =NewHandler () {@Override     Public void Handlemessage(Message msg) {// ...}    }@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Post a message and delay its execution for ten minutes.Mleakyhandler.postdelayed (NewRunnable () {@Override       Public void Run() {/* ... */}    }, the);//Go to the previous Activity.Finish (); }}
//Improvement mechanism* * Of course, when the activity is destroyed should also cancel the corresponding task Asynctask.cancel (), to avoid tasks in the background waste resources * *。 Public  class mainactivity extends appcompatactivity {        PrivateMyHandler Mhandler =NewMyHandler ( This);PrivateTextView Mtextview;Private Static  class myhandler extends Handler {            PrivateWeakreference<context> reference; Public MyHandler(Context context) {reference =NewWeakreference<> (context); }@Override             Public void Handlemessage(Message msg) {Mainactivity activity = (mainactivity) reference.get ();if(Activity! =NULL) {Activity.mTextView.setText (""); }            }        }@Override        protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);            Setcontentview (R.layout.activity_main);            Mtextview = (TextView) Findviewbyid (R.id.textview);        LoadData (); }Private void LoadData() {//...requestMessage message = Message.obtain ();        Mhandler.sendmessage (message); }//Note release        @Override        protected void OnDestroy() {Super. OnDestroy (); Mhandler.removecallbacksandmessages (NULL); }    }
5. Non-static internal class creates a memory leak caused by a static instance
/ * This creates a single instance of a non-static inner class within the activity and uses the singleton data each time the activity is started, which avoids duplication of resources, but this writing can cause a memory leak because the non-static inner class holds a reference to the external class by default. The non-static inner class is used to create a static instance with the same life cycle as the application, which causes the static instance to hold a reference to the activity, causing the memory resource of the activity not to be recycled properly. The correct approach is to set the inner class as a static inner class or to extract the inner class into a single case, if you need to use the context, use the applicationcontext*/     Public  class mainactivity extends appcompatactivity {        Private StaticTestresource Mresource =NULL;@Override        protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);if(Mmanager = =NULL) {Mmanager =NewTestresource (); }//...} class Testresource {//...}    }
6. Memory leaks due to listener registration

In the Observer pattern,
Event listeners and callbacks. A memory leak can occur if a class registers a listener, but does not unregister the listener after the class is no longer in use.

//The Observer class first to establish a unified observer collector collection,  public  class  listenercollector  { static  private  Weakhashmap<view, myview.mylistener> Slistener = new  weakhashmap<> (); public  void  setslistener  (View view, Myview.mylistener Listener) {slistener.put (view,listener);} //solution  public  static  void  clearlisteners  () {//hashmap remove the listener.  slistener.clear (); };}
 Public  class MyView extends View{     Public  MyView(Context context) {Super(context);    Init (); } Public  interface mylistener{         Public void Mylistenercallback(); }Private void Init() {Listenercollector collector =NewListenercollector (); Collector.setslistener ( This, MyListener); }PrivateMyListener MyListener =NewMyListener () {@Override         Public void Mylistenercallback() {System.out.print ("has been called"); }    };}
//activity调用处  @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        new MyView(this);        setContentView(myView);    }//解决方案    @Override    protectedvoidonStop() {        super.onStop();        ListenerCollector.clearListeners();    }
7. Memory leaks due to resource not shutting down

For use of resources such as Braodcastreceiver,contentobserver,file,cursor,stream,bitmap, should be closed or cancelled when the activity is destroyed , Otherwise, these resources will not be recycled, causing a memory leak.

6. Memory Leak Summary

1. For objects with a longer life cycle than the activity, use ApplicationContext if needed

2, in the context of the first consideration of ApplicationContext, of course, it is not omnipotent, for some places must use the context of activity, for Application,service, The context scenario for activity three is as follows:
Write a picture description here

Where: NO1 indicates that application and service can initiate an activity, but a new task queue is required to be created. For dialog, it is only in activity that you can create

3. For non-static external member variables (such as: Context, View) that need to be used in static internal classes, you can use weak references in static inner classes to refer to variables of external classes to avoid memory leaks

4. For internal class objects that have a longer life cycle than the activity, and the inner class uses the member variables of the outer class. changing an inner class to a static inner class, using a weak reference in a static inner class to refer to the member variable of the outer class

5. For objects that are no longer needed, the display assigns them null, such as calling recycle () before bitmap is used, and then assigning null

6, keep the object life cycle sensitive , pay special attention to the life cycle of single case, static object, global collection, etc.

About Me

GitHub Address
Personal Technology Development Blog
Android Advanced Growth Group: 570381965

Deep Android Memory leaks

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.