Memory leaks and memory overflow

Source: Internet
Author: User
Tags message queue static class

Recent projects frequently appear oom problems, various path testing, memory trend analysis, all kinds of logical reasoning to finally locate the problem. In this process and group of students to discuss the time found that some students of memory leaks and memory overflow concept is not in place, resulting in a more embarrassing communication process. Many students do not understand these two concepts thoroughly, in the project frequently write out a memory leak of low-level code out. Combining my own understanding I write an article to understand these two concepts. Memory Leaks

Memory leaks are the phenomenon that memory objects that should be recycled (no longer used) cannot be reclaimed by the system. In C + + requires program ape manually frees memory objects, so there is a greater vulnerability to memory leaks in C + +. Java introduces the automatic recycling mechanism, which makes the memory problem in C + + more effective, but this does not mean that the Java programmer is not concerned about memory because the garbage collection mechanism does not fully guarantee that the memory object is released where it is released. In modern Java virtual machines, the root set algorithm is commonly used to compute the reference accessibility of objects, and can not be recovered, for example, the unwanted objects in the figure below are referenced by useful objects, which leads to useless object references, which are not able to be recovered by the system collector, thus causing memory leaks.

Memory Overflow

When the system allocates memory for a segment execution instruction (program), it discovers that there is not enough memory to throw an error, which is called a memory overflow.

The relationship between the two

Mobile phone device memory space is limited, for each application allocated to the memory space is limited, when the memory leak object more and more, can be leveled memory space is smaller, app application performance is worse, when the amount of memory space can not be provisioned to create a new object will cause oom.

Memory leak Classic Model Static Variables

The life cycle of a static variable is the longest, and as with the application lifecycle, when a large object is referenced by a static variable of a class, the object cannot be reclaimed by the system and consumes memory throughout its lifecycle. Common in the tool class, the general existence of a large number of tool classes, many students to facilitate the direct or indirect use of static variables to refer to a context object.

public class Notificationutil { 
 //static variable, Notificationmanager leak
  private static  Notificationmanager Notificationmanager;   
  public static void notification (context context, class<?> CLS, message msg) {   
     if (Notificationmanager = null) { C5/>notificationmanager = (Notificationmanager)       
        context.getsystemservice (context. Notification_service);   
      }
    //....
 }
}

The Notificationmanager object is leaking, and because there is a context object Mcontext variable in the Notificationmanager object, it is back to cause a contextual object leak that started the method.

Avoid:

For tool classes, such as infrequently used objects, try not to use static variables to reference, can be created at the time of the method execution, as a local variable to use, if you need to frequently use, in order to improve the efficiency of method execution, for the above situation can be restricted to the context parameter application Level to prevent the caller from passing the context of the activity level, causing an activity leak.

public class Notificationutil { 
 //static variable
  private static  Notificationmanager Notificationmanager;   
  public static void notification (application context, class<?> CLS, message msg) {   
    //context limited to application level C5/>if (Notificationmanager = = null) {    
        Notificationmanager = (notificationmanager)       
        Context.getsystemservice ( Context. Notification_service);   
      }
    //.....
 }
}
Single case Mode

A single example is actually a kind of static variable, the life cycle of a single example is the same as a static variable, and if this single example holds a large object, it can cause this large object to leak.

private static webviewclient instance;
public static webviewclient getinstance {   
 if (instance = null) {  
    //mcontext risk
    of leakage Instance = new Webviewclient (context, Jstojava); 
  }   
 return instance;
} 

For example, the mcontext here, if it is an activity, will be cited by instance for a long time.

Avoid:

As with static variables, try to use the context of the application level instead of the activity level context.

private static webviewclient instance;
The public static Webviewclient getinstance (Application context) {   
  //context restricted to application level
 if (instance = null {  
    instance = new Webviewclient (context, Jstojava); 
  }   
 return instance;
}
Inner class

Because the existence of an inner class relies on its external class, it is possible for some reasons that the internal class to be referenced will not exit, causing the outer class to be recyclable, which is the most frequently used memory leak.


Internal class loops or blocks, there is a wonderful code below, a graduate student wrote:

Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.widget.EditText;
public class Checkedittext extends edittext{public
 checkedittext (context Context,attributeset attrs) {
  Super (CONTEXT,ATTRS);
  New Thread () {
   @Override public
   void Run () {while
      (true) {
         String content = This.gettext (). toString ();
         if (Content.length () >) {
            //character length cannot be greater than//...}}}}
  . Start ();
 }

Then all the activity that uses this checkedittext is leaking.

The most common of this pattern is the use of handler, which is the model for many memory leaks in the general project:

Internal class Handler, there is a memory leak risk
Handler Handler = new Handler () {public
    void Handlemessage (Android.os.Message msg) {
        int what = Msg.what;
        Switch (what) {case show
            :
                progressdialog = progressdialog.show (detailactivity.this, null, "Picture crosses ...");
                break;
            Case DISMISS:
                if (progressdialog!= null && progressdialog.isshowing ()) {
                    Progressdialog.dismiss ();
                } break
                ;
            Case Uploadpic:
                string base64imagestring = (string) msg.obj;
                Webview.loadurl ("Javascript:filechoosercallback" ("+" "" + base64imagestring
                        + "" + ")");
                break;

            Default: Break;}}

;

This is a handler inner class in Detailactivity, which causes detailactivity to leak because handler is actually referenced by a message queue.

Avoid:

For those that may be long-running, blocked, or externally referenced internally, try to use static internal classes instead. The existence of a static internal class object does not depend on the external class, which avoids the implicit reference to the external class of the internal classes, and then holds the external class object with the weak reference.

 Static class MyHandler extends Handler {//Static internal class instead, and use if the reference holds detailactivity private Weakreference<detailactiv
    Ity> WeakReference;
    Public MyHandler (detailactivity activity) {this.weakreference = new weakreference (activity);
        public void Handlemessage (Android.os.Message msg) {int what = Msg.what;
        Detailactivity activity = Weakreference.get ();
        if (activity = null) {return; Switch (what) {case SHOW:activity.progressDialog = progressdialog.show (activity, n
                Ull, "The picture Crosses ...");
            Break
                    Case Dismiss:if (activity.progressdialog!= null && activity.progressDialog.isShowing ()) {
                Activity.progressDialog.dismiss ();
            } break;
                Case uploadpic:string base64imagestring = (String) msg.obj; ACTIVITY.WEBVIEW.LOADURL ("Javascript:filechoosercallBack ("+" "" + base64imagestring + "' +") ");
            Break
        Default:break;
}

    }
};
 MyHandler handler = new MyHandler (this);

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.