Thread of memory leak for Android App

Source: Internet
Author: User

Thread Memory leak
线程也是造成内存泄露的一个重要的源头。线程产生内存泄露的主要原因在于线程生命周期的不可控。
1. See if any of the following problems exist
<span style= "White-space:pre" ></span>/** *  * @version 1.0.0  * @author Abay Zhuang <br/> *   Create at 2014-7-17 */public class Threadactivity extends Activity {public void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); new MyThread (). Start (); Private class MyThread extends Thread {@Overridepublic void run () {Super.run ();d osomthing ();}} private void Dosomthing () {}}



This piece of code is very common and very easy, which is the form we often use.

Is there really no problem?
我们思考一个问题:如果MyThread的run函数是一个非常费时的操作,当我们开启该线程后,将设备的横屏变为了竖屏。普通情况下当屏幕转换时会又一次创建Activity,依照我们的想法。老的Activity应该会被销毁才对,然而其实并不是如此。

因为我们的线程是Activity的内部类。所以MyThread中保存了Activity的一个引用,当MyThread的run函数没有结束时,MyThread是不会被销毁的。因此它所引用的老的Activity也不会被销毁。因此就出现了内存泄露的问题。

2. What should be done to solve the memory leak problem caused by such a thread?
  • First, the internal class of the thread is changed to a static inner class.
  • Second, the thread internally adopts a weak reference to save the context reference. The code is as follows:

    <span style= "White-space:pre" ></span>/** *  * @version 1.0.0 * @author Abay Zhuang <br/> *         Create at 2014-7-17 */public class Threadavoidactivity extends Activity {public void onCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); new MyThread (This). Start (); private void Dosomthing () {}private static class MyThread extends Thread {weakreference<threadavoidactivity> Mthreadactivityref;public MyThread (threadavoidactivity activity) {mthreadactivityref = new weakreference< Threadavoidactivity> (activity);} @Overridepublic void Run () {super.run (); if (mthreadactivityref = = null) return;if (mthreadactivityref.get () = null) Mthreadactivityref.get (). dosomthing ();//Dosomthing}}}


The two steps above are in fact a two-way strong reference link to toggle two objects
    1. Static inner class: Cut off the activity's strong reference to Mythread.
    2. Weak references: Cut off Mythread's strong references to activity.
What happens to the 3.AsynTask inner class?
 Some people like to use Android to provide asynctask. But in fact, the problem of asynctask is even more serious, thread only in the run function is not the end of such a memory leak problem, but asynctask internal implementation mechanism is the use of Threadpoolexcutor, The life cycle of the thread object produced by this class is indeterminate. is beyond the control of the application. So assuming asynctask as the inner class of activity, it's easier to have a memory leak problem. 

code such as the following:

/** * * Weak citation * @version 1.0.0 * @author Abay Zhuang <br/> * Create at 2014-7-17 */public abstract class Wea Kasynctask<params, Progress, Result, weaktarget> extends Asynctask<params, Progress, result> {protected Wea Kreference<weaktarget> mtarget;public Weakasynctask (weaktarget target) {mtarget = new Weakreference<weaktarg Et> (target);}    @Overrideprotected final void OnPreExecute () {final Weaktarget target = Mtarget.get ();    if (target! = null) {This.onpreexecute (target);    }} @Overrideprotected final Result doinbackground (params ... params) {final Weaktarget target = Mtarget.get ();    if (target! = null) {return This.doinbackground (target, params);    } else {return null;    }} @Overrideprotected final void OnPostExecute (result result) {final Weaktarget target = Mtarget.get ();    if (target! = null) {This.onpostexecute (target, result); }}protected void OnPreExecute (Weaktarget target) {//Nodefaultaction}protected abstract Result doinbackground (weaktarget target, params ... params);p rotected void OnPostExecute (weaktarget target, result result) {//Nodefaultaction}}


Thread of memory leak for Android App

Related Article

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.