Welcome to the Csdn-markdown Editor

Source: Internet
Author: User

Introduction to memory leaks

The memory leak is for the heap memory.

The memory management of Java is the allocation and release of objects. Memory allocations are performed by the program, and the release of the memory is done by the GC. GC can only reclaim space occupied by objects that are useless and not referenced by other objects.
Extending from the main method, all reachable objects are valid objects that make up the collection of objects that cannot be recycled. Other orphaned objects are the target of GC recycling.

    {        ObjectnewObject();    }

The life cycle of a local variable is the end of the curly brace. At this point, the O in the stack is destroyed, and the object of the new object () is not referenced, becomes an orphaned object, and is recycled by GC.
Therefore, the root cause of the memory leak is that a long life-cycle object in heap memory holds a strong/soft reference to a short-life-cycle object, although the short-life-cycle object is no longer needed, because the long-life-cycle object holds a reference to him that prevents him from being recycled.

Common memory leaks
    • Collection

      集合如果只有添加方法,没有删除方法,内存会被大量占用。如果集合是全局的,会造成内存只增不减。
    • Single case

      A singleton object will exist throughout the JVM's lifetime after it is initialized, and if the singleton holds an external object, the external object cannot be recycled, causing a memory leak.

publicclass Test{    privatestatic Test test;    private Context context;    privateTest(Context context){        this.context = context;    }    publicstaticgetInstance(Context context){        ifnull){            new Test(context);        }        return test;    }}

If the incoming context is an activity, the activity persists in memory and cannot be freed.

    • Various components in Android

      Broadcastreceiver,contentobserver,cursor, etc., after regist, remember to call unregister or close () at the end, and do not use activity as a member variable, such as the use of the preceding singleton. If necessary, remember to use WeakReference.

    • Non-static inner class

 Public  class mainactivity extends appcompatactivity {    Private StaticTestresource Mresource =NULL;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);if(Mresource = =NULL) {Mresource =NewTestresource (); }//...} class Testresource {//...}}

The lifetime of the static member Mresource of the outer class is the run time of the entire program, and the object of the inner class defaults to a reference to the external Category object, causing the activity to not be freed.
You can define an inner class as a static inner class, and you can cut off the relationship between the inner class and the object of the outer class, only with respect to the class.

    • Memory leaks caused by threads

      Because the life cycle of a thread is not controllable, if a thread holds a reference to an external object, it causes the external object to be non-free.

    • Memory leaks caused by handler

      If the message sent by handler is not processed, then MessageQueue will keep a reference to Handler,message, and handler is inconsistent with the activity's life cycle. May cause activity to not be released smoothly.

 Public  class sampleactivity extends Activity {Private FinalHandler Mleakyhandler =NewHandler () {@Override     Public void Handlemessage(Message msg) {// ...}}@Overrideprotected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Post a message and delay its execution for ten minutes.Mleakyhandler.postdelayed (NewRunnable () {@Override       Public void Run() {/* ... */}    }, +* -*Ten);//Go to the previous Activity.Finish (); }}

The above code, sent a deferred message, when the message is not processed, the page exit will cause the page can not be recycled.

Precautions
    • Reference to activity takes into account the activity's life cycle, but cannot control its life cycle, consider using getapplicationcontext () to avoid the activity being occupied for a long time.
    • Try not to use non-static member variables in the static inner class, you must use it, or you can set it to null at the appropriate time, or use a weak reference in a static inner class to refer to the external member variable.
    • Handler holds a reference object preferably a weak reference, and when the resource is released, the message in handler can be emptied.
    • Thread processing time-consuming operations, even if canceled when the page returns.

Welcome to the Csdn-markdown Editor

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.