Android匿名asyncTask-是否会导致内存泄漏 [英] android anonymous asyncTask - will it cause memory leak

查看:243
本文介绍了Android匿名asyncTask-是否会导致内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在android中,我试图防止内存泄漏.我继承了一些旧代码,开发人员在其中创建了asyncTask作为匿名内部类,如下所示:

In android i am trying to prevent a memory leak. I inherited some legacy code and in it the developer is creating a asyncTask as a anonymous inner class like this:

 void startAsyncTask() {
    new AsyncTask<Void, Void, Void>() {
        @Override protected Void doInBackground(Void... params) {
            while(true);//loop  to keep thread alive forever.
        }
    }.execute();
}

所以我在这个例子中使用循环只是为了使子线程永远活着,这样我就可以演示我的观点了. 所以从活动中如果我呼叫startAsyncTask()会不会发生内存泄漏?该类没有活动引用,但我意识到匿名类实际上是一个非静态内部类,因此拥有对外部类的引用.那么这本身就是内存泄漏吗?

so i am using a loop in this example just to keep the child thread alive forever so i can demo my point. so from the activity if i call startAsyncTask() will there be a memory leak ? the class does not have a activity reference but i realize that an anonymous class is really a non-static inner class and thus holds a reference to the outer class. so is it true that this itself is a memory leak ?

推荐答案

它将保留对外部类(活动)的引用,直到任务完成.因此,这将使活动的举行时间超过绝对必要的时间.但是,如果任务在合理的时间内完成,那应该没问题-完成任务后,任务将结束并变为可垃圾回收,这将使Activity可以被垃圾回收.更大的问题是长期线程可能会持续到活动结束之后,或者如果编写得不好则根本不会终止.

It will hold a reference to the outer class (the Activity) until the task finishes. So it will cause the activity to be held longer than absolutely necessary. However if the task finishes in a reasonable amount of time, that ought to be ok- after its finished the task will be over and become garbage collectable, which will make the Activity garbage collectable. The bigger concern is long term threads which can last well past the end of the activity, or not terminate at all if poorly written.

这篇关于Android匿名asyncTask-是否会导致内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆