Handler memory leak issues

Source: Internet
Author: User

Handler a memory leak problem?

The so-called memory leak is that this object does not have any use value, but because there is still a reference to the memory is occupied by the garbage collector can not be recycled ....
Why is there a memory leak?
The principle in this is deep and deep, because the new handler is an inner class object that has a hidden-test-strong reference to the external partial object.
Internal classes There is a hidden test strong reference to the external class does not lead to a memory leak, although the activity of the reference is held by the inner class object, the big deal inside class objects are first recycled, external classes can be recycled, The key is because I specifically emphasized in the previous article that there is a msg.target=this inside the handler, this inner class handler is held by messages in the message queue, so as long as there is a message in the message queue, the handler cannot be cleaned up. This causes the activity of the external class to not be recycled by the GC, even if it exits, so that the memory leaks. Based on my point of this, I can now solve this memory leak from three points.
Extension of the Knowledge point:
There are four references in Java, the environment Search algorithm and a recycling algorithm when garbage collector recycles garbage.
The search algorithm uses a reference counting algorithm, an object is an object traversal, when an object is not referenced by others when the counter will be added 1, if the reference disappears, the counter will be reduced by one, when the reference counter is 0,ok. The garbage collection period is listed as a recyclable object, and the GC runs out of regular cleanup and frees up memory. When our internal classes are created, the external class will have a strong reference to the implicit test. The so-called implicit test, we can not see, but the virtual machine is designed to have a reference
Because it is a strong reference, this inner class object can never be cleaned out, but when we exit the interface, the mainactivity of the outer class should be cleaned up, but the activity object will never be cleaned up because of a reference to the inner class. and this internal class due to Messagequeen in the Meg has a reference to it, so the handler can not clean up, so the activity will not clean up, so lead to memory leaks, the solution is to set handler static, So there is no implicit test strong reference relationship between static inner class and external classes.

Four types of reference,
1: Strong reference. When an object is referenced by a strong reference, the GC will never be able to clean it off, unless Oom, the virtual machine is dead, and it must be dead.
2: Soft reference, when the system memory is low when the GC off
3: Weak reference, when the GC found it to kill it. By extension, if you add a queen to this weak reference (remember that there is an overloaded method to add this parameter), the referenced reference will be put into this queen, and then we can detect if the Queen is null to see if the object has not been cleaned, the null description has not been cleaned, Non-null description is cleared, memory detection public leakcanary Use this principle to do, in more than one mouth, memory detection public and MAT,DDMS heap can be detected
4: Virtual reference, not a true reference type, is used to detect memory leaks

1: The first solution to handler static so there is no internal class implicit test strong reference problem

This method of submission:

2: There is also a solution is to use a soft reference. When the memory is not enough to clean up, we inherit the handler class, and then we create this custom handler object into its own new soft reference, so that when the memory is low, the soft reference object will be cleaned out

 @Override  protected  void  oncreate  (        Bundle savedinstancestate) {super . OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        MyHandler2 = new  Myhandler2 ();    SoftReference = new  softreference
class Myhandler2 extends Handler{ WeakReference<Context> weak;} @Override public void handleMessage(Message msg) { String s=(String)msg.obj; Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show(); super.handleMessage(msg); }}//点击按钮实现的子线程向主线程传消息public void click(View v){ new Thread(new Runnable() { @Override public void run() { Message msg=new Message(); msg.what=13; msg.obj="dasdasd"; softReference.get().sendMessage(msg); } }).start();}

3: Third message to clean up Message Queuing
is to call myhandler2.removecallbacksandmessages (null) at the Destory or finish of the activity, so that the message is emptied, there is no meg.target=handler. Employment does not exist this Messagequeen message holds this handler reference, so that handler can be cleaned up.

Handler memory leak issues

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.