android resolves memory overflow issues

Source: Internet
Author: User

2011-03-11 00:03:57 Tags: memory leaks android OutOfMemory Bitmap cursor copyright notice: Original works, declined reprint! Otherwise, the legal liability will be investigated. One, the Android memory mechanism Android program is written by the Java language, so Android memory management and Java memory management similar. The programmer allocates memory for the object through new, and all objects allocate space within the Java heap, while the object's release is done by the garbage collector. C + + memory mechanism is "who pollution, who governance", Java is more humane, give us a dedicated cleaner (GC). So how can a GC confirm that an object has been discarded? Java uses the principle of a forward graph. Java considers the reference relationship as a directed edge of the graph, and has a pointing edge from the referrer to the Reference object. The thread object can serve as the starting vertex of a forward graph, which is a tree starting from the starting vertex, the objects that the root vertices can reach are valid objects, and the GC does not reclaim those objects. If an object (connected sub-graph) and this root vertex are unreachable (note that the graph is a forward graph), then we think that this (these) objects are no longer referenced and can be recycled by GC. Second, Android memory overflow how does Android memory overflow occur? Android virtual machine is a register-based Dalvik, its maximum heap size is generally 16M, and some machines are 24M. So the amount of memory space we can use is limited. OutOfMemory errors occur if our memory footprint exceeds a certain level. Why is there a situation where memory is not enough? I think there are two main reasons: due to our program errors, long-term maintenance of certain resources (such as the context) of the reference, resulting in memory leaks, resources caused by the failure to release. Multiple objects that consume too much memory (such as bitmap) are saved, causing memory to exceed the limit. Three, the evil static static is a keyword in Java, when it is used to modify the member variable, then the variable belongs to the class, not the instance of the class. So with the static modified variable, its life cycle is very long, if it is used to reference some resources to consume too many instances (the context of the most cases), then it should be treated with caution. public class ClassName {private static Context mcontext;//omit} The code above is very dangerous if the activity is assigned to Mcontext. So even if the activity is OnDestroy, the activity will not be released because there is still a reference to the object that holds it. We lift the Android documentAn example of this. private static drawable Sbackground; @Override protected void OnCreate (Bundle state) {super.oncreate (state); TextView label = new TextView (this); Label.settext ("Leaks is bad"); if (Sbackground = = null) {Sbackground = getdrawable (R.drawable.large_bitmap);} label.setbackgrounddrawable ( Sbackground); Setcontentview (label); } Sbackground, is a static variable, but we found that we did not explicitly save the Contex reference, but when drawable is connected to the view, drawable sets the view to a callback, Because the view is a reference to the context, in fact we still have a reference to the context. This reference chain is as follows: Drawable->textview->context So, eventually the Context was not released, and a memory leak occurred. How can we effectively avoid the occurrence of such a reference? First, you should avoid static member variables referencing resources that consume too many instances, such as context. Second, the context as far as possible to use application context, because the application context of the life cycle is relatively long, reference it will not be a memory leak problem. Third, use WeakReference instead of strong references. For example, you can use WeakReference mcontextref; The details of this section can also refer to the article section of the Android documentation. Four, threads are the thread of the thread is also an important source of memory leaks. The main reason for a thread's memory leak is that the thread life cycle is not controllable. Let's consider the following section of code. public class MyActivity extends Activity {@Override public void onCreate (Bundle savedinstancestate) {super.oncreate (save Dinstancestate); Setcontentview (R.Layout.main); New MyThread (). Start (); } private class MyThread extends thread{@Override public void Run () {super.run ();//do somthing}}} This code is very common and simple, and we often make In the form of use. Let's think of a problem: assuming that the mythread run function is a time-consuming operation, when we turn on the thread, we turn the device's horizontal screen into a vertical screen, and normally the activity is recreated when the screen is converted, as we thought, the old activity should be destroyed. However, this is not the case in fact. Since our thread is the inner class of activity, a reference to activity is saved in Mythread, and when Mythread's run function does not end, Mythread is not destroyed, so the old activity it references is not destroyed. Therefore, there is a memory leak problem. Some people like to use Android-provided asynctask, but in fact the asynctask problem is even more serious, and thread only has this memory leak problem when the run function does not end. However, the implementation mechanism within the asynctask is the use of threadpoolexcutor, the life cycle of the thread object produced by this class is indeterminate and is beyond the control of the application, so if Asynctask is the inner class of activity, The problem of memory leaks is more likely. How should the memory leak problem caused by this thread be resolved? First, the internal class of the thread is changed to a static inner class. Second, use weak references inside the thread to save the context reference. The model is resolved as follows: Public abstract class Weakasynctask extends Asynctask {protected weakreference mtarget; public Weakasynctask (Wea Ktarget target) {mtarget = new WeakReference (target),}/** {@inheritDoc} */@Override protected final void OnPreExecute ( {Final Weaktarget target = Mtarget.get (); if (target! = null) {This.onpreexecute(target); }}/** {@inheritDoc} */@Override protected final Result doinbackground (params ... params) {final Weaktarget target = MTa Rget.get (); if (target! = null) {return This.doinbackground (target, params);} else {return null;}} /** {@inheritDoc} */@Override protected final void OnPostExecute (result result) {final Weaktarget target = Mtarget.get () ; if (target! = null) {This.onpostexecute (target, result);}} protected void OnPreExecute (Weaktarget target) {//No default action} protected abstract Result Doinbackground (weaktarge T target, params ... params); protected void OnPostExecute (weaktarget target, result result) {//No default action}} In fact, threading problems are not just memory leaks, but also some catastrophic problems. 。 Because this article discusses memory issues, there is no discussion here.

Android resolves memory overflow 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.