"Reprinted" Thread of Memory leaks in Android App

Source: Internet
Author: User

Reprint Address http://blog.csdn.net/zhuanglonghai/article/details/37909553

Thread Memory leak
线程也是造成内存泄露的一个重要的源头。线程产生内存泄露的主要原因在于线程生命周期的不可控。
1. See if there is a problem
<span style= "White-space:pre" > </span>/**     *      * @version1.0.0 *@authorAbay Zhuang <br/> * Create at 2014-7-17*/     Public classThreadactivityextendsActivity { Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);            Setcontentview (R.layout.activity_main); NewMyThread (). Start (); }            Private classMyThreadextendsThread {@Override Public voidrun () {Super. Run ();            Dosomthing (); }        }        Private voiddosomthing () {}}

This code is very common and simple, it is the form that 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 this thread?

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 code is as follows:

<span style= "White-space:pre" > </span>/**         *          * @version1.0.0 *@authorAbay Zhuang <br/> * Create at 2014-7-17*/                 Public classThreadavoidactivityextendsActivity { Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.activity_main); NewMyThread ( This). Start (); }                    Private voiddosomthing () {}Private Static classMyThreadextendsThread {weakreference<ThreadAvoidActivity>Mthreadactivityref;  PublicMyThread (threadavoidactivity activity) {Mthreadactivityref=NewWeakreference<threadavoidactivity>(activity); } @Override Public voidrun () {Super. Run (); if(Mthreadactivityref = =NULL)                        return; if(Mthreadactivityref.get ()! =NULL) Mthreadactivityref.get (). dosomthing (); //dosomthing                }            }        }

The above two steps are actually 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?
有些人喜欢用Android提供的AsyncTask,但事实上AsyncTask的问题更加严重,Thread只有在run函数不结束时才出现这种内存泄露问题,然而AsyncTask内部的实现机制是运用了ThreadPoolExcutor,该类产生的Thread对象的生命周期是不确定的,是应用程序无法控制的,因此如果AsyncTask作为Activity的内部类,就更容易出现内存泄露的问题。

The code is as follows:

/*** * Weak references *@version1.0.0 *@authorAbay Zhuang <br/> * Create at 2014-7-17*/ Public Abstract classWeakasynctask<params, Progress, Result, weaktarget>extendsAsynctask<params, Progress, result> {protectedWeakreference<weaktarget>Mtarget; PublicWeakasynctask (weaktarget target) {mtarget=NewWeakreference<weaktarget>(target);} @Overrideprotected Final voidOnPreExecute () {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) {         This. OnPreExecute (target); }} @Overrideprotected FinalResult doinbackground (params ... params) {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) {        return  This. Doinbackground (target, params); } Else {        return NULL; }} @Overrideprotected Final voidOnPostExecute (Result result) {FinalWeaktarget target =Mtarget.get (); if(Target! =NULL) {         This. OnPostExecute (target, result); }}protected voidOnPreExecute (weaktarget target) {//nodefaultaction}protected AbstractResult Doinbackground (weaktarget target, params ... params);protected voidOnPostExecute (weaktarget target, result result) {//nodefaultaction}}

"Reprinted" Thread of Memory leaks in Android App

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.