Analysis of the causes of memory leakage caused by internal handler of activity

Source: Internet
Author: User

Sometimes a memory leak warning is prompted when using handler in activity, and the code is usually as follows:

[Java]View Plaincopyprint?
  1. Public class Mainactivity extends Activity {
  2. private TextView Tvhelloworld;
  3. private Button Btnsettext;
  4. private Handler Mhandler = new Handler ();
  5. @Override
  6. protected void OnCreate (Bundle savedinstancestate) {
  7. super.oncreate (savedinstancestate);
  8. Setcontentview (R.layout.activity_main);
  9. Btnsettext = (Button) Findviewbyid (R.id.btn_set_text);
  10. Tvhelloworld = (TextView) Findviewbyid (R.id.tv_hello_world);
  11. Btnsettext.setonclicklistener (new Onclicklistener () {
  12. @Override
  13. public void OnClick (View v) {
  14. Mhandler.post (new Runnable () {
  15. @Override
  16. public Void Run () {
  17. Tvhelloworld.settext ("Runnable");
  18. }
  19. });
  20. }
  21. });
  22. }
  23. }

The original Lint warning is as follows:

This Handler class should is static or leaks might occur (com.example.testhandler.mainactivity.1)

Issue:ensures that Handler classes does not hold on to a reference to an outer class
Id:handlerleak

Since This Handler is declared as a inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread and other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follow S:declare the Handler as a static class; In the outer class, instantiate a weakreference to the outer class and pass this object to your Handler when you Instantia Te the Handler; Make all references to the outer class using the WeakReference object.

1. Memory Leak cause Analysis

Since this handler is declared inside the activity as an inner class object, the ordinary inner class objects implicitly hold a reference to the Outer class object, so the handler object holds a reference to the Activity object. The life cycle of this handler object may be more than the activity life cycle field, such as when there is a background thread holding the handler, and the thread is performing a lengthy task. So when the handler is not reclaimed by the JVM garbage collector, it prevents the recycling of the external class activity objects it references, causing a memory leak.


2. How to resolve this memory leak problem

A method for solving this problem is given in the memory-leaking lint warning. Declare the handler class as a static inner class that unlocks the connection between the inner class object and its outer class object. Creates an weakreference of an external class and uses it when instantiating a handler object. The code is implemented as follows:

[Java]View Plaincopyprint?
  1. Public class Mainactivity extends Activity {
  2. private TextView Tvhelloworld;
  3. private Button Btnsettext;
  4. private Handler Mhandler = new Internalhandler (this);
  5. @Override
  6. protected void OnCreate (Bundle savedinstancestate) {
  7. super.oncreate (savedinstancestate);
  8. Setcontentview (R.layout.activity_main);
  9. Btnsettext = (Button) Findviewbyid (R.id.btn_set_text);
  10. Tvhelloworld = (TextView) Findviewbyid (R.id.tv_hello_world);
  11. Btnsettext.setonclicklistener (new Onclicklistener () {
  12. @Override
  13. public void OnClick (View v) {
  14. Mhandler.post (new Runnable () {
  15. @Override
  16. public Void Run () {
  17. Tvhelloworld.settext ("Runnable");
  18. }
  19. });
  20. }
  21. });
  22. }
  23. private static class Internalhandler extends Handler {
  24. private weakreference<activity> weakrefactivity;
  25. /** 
  26. * A constructor that gets A weak reference to the enclosing class. We
  27. * Do this to avoid memory leaks during Java garbage Collection.
  28. */
  29. Public Internalhandler (activity activity) {
  30. weakrefactivity = new weakreference<activity> (Activity);
  31. }
  32. @Override
  33. public void Handlemessage (Message msg) {
  34. Activity activity = Weakrefactivity.get ();
  35. if (activity! = null) {
  36. }
  37. }
  38. }
  39. }


3. SoftReference, WeakReference and Phantomreference

SoftReference, WeakReference, and Phantomreference are a set of classes in the Java.lang.ref class library. These 3 classes provide different levels of indirection for the garbage collector when the object being inspected by the garbage collector is "available" only through a reference object.

An object is available (reachable), meaning that the object can be found somewhere in the program. This means that you have a normal "reference a" in the stack, and it is pointing to this "object a", or "reference B" to "Object B", while "Object B" contains "reference C" pointing to "object a" or more intermediate links. If an object is "available", the garbage collector cannot release it because it is still used by your program. If an object is not "available", then your program will not be able to use it, so it is safe to recycle it.

You should use the Reference object if you want to continue to hold a reference to an object, want to be able to access the object later, and want the garbage collector to reclaim it when the memory is exhausted.

SoftReference, WeakReference, and phantomreference are arranged from strong to weak, indicating different levels of "availability".

SoftReference is used to implement memory-sensitive caches.

WeakReference is designed to implement a canonical mapping (canonicalizing mappings) and does not prevent the garbage collector from reclaiming the "Keys" (or "values") of the mappings. An instance of an object in spec map can be used in multiple places in a program to save storage space.

Phantomreference is used to schedule cleanup before recycling, which is more flexible than the Java termination mechanism.

Analysis of the causes of memory leakage caused by internal handler of activity

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.