内存泄漏:用Java垃圾收集之间的混淆 - 和Android杀害机制? [英] Memory leak: Confusion between Java Garbage Collector - and Android killing mechanism?
问题描述
我是新手,Java和Android的,目前我在Android中感到困惑的内存泄漏,比如:我有01类,01活动和01接口如下:
I am newbie to both Java and Android, and currently I am confused about "memory leak" in Android, for example: I have 01 Class, 01 Activity and 01 Interface as following:
类BackgroundWorker的是一个单独的,只要它生活在应用程序的生命:
Class BackGroundWorker is a singleton, which lives as long as the application lives:
public class BackGroundWorker {
private IOnEventOccurListener listener = null;
private static BackGroundWorker instance;
// ....
public void setListener(IOnEventOccurListener pListener) {
this.listener = pListener;
}
// ....
public static BackGroundWorker getInstance() {
//...
return instance;
}
}
监听器接口:
The Listener Interface:
public interface IOnEventOccurListener {
public void onEventOccur();
}
和监听器本身(的活动):
And the Listener itself (An activity):
public class ShowSomething extends Activity implements IOnEventOccurListener{
BackGroundWorker bgWorker;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bgWorker = BackGroundWorker.getInstance();
bgWorker.setListener(this);
}
@Override
public void onEventOccur() {
// TODO do something
}
}
现在,根据是什么罗曼盖伊这里一提到 >: 这是一个内存泄漏,因为有一个参考监听器(活动)。所以Java GC无法收集活动,即使在不使用。
Now, according to what Romain Guy mentioned here: It’s a memory leak, because there’s a reference to the listener (Activity). So Java GC cannot collect the Activity, even when it’s not in use.
我能够WeakReference的解决这个问题 - 但仍然不知道: 在这种情况下,当设备需要更多的内存,据Android开发文档,它会杀的活动如果需要的话 - 假设活动ShowSomething被封杀 - 然后会发生什么? (它仍然按照罗曼盖伊泄漏,而且还封杀)
I was able to solve that problem by WeakReference – but still wonder: In this case, when the device needs more memory, according to Android Dev document, it will "kill" the activity if needed - assuming that the Activity ShowSomething is "killed" – then what happens ? (It’s still leak according to Romain Guy, and still "killed" )
我真的很困惑。可能有人请解释一下吗?
I am really confused. Could anybody please explain this ?
感谢您先进,
儿子
Thank you in advanced,
Son
推荐答案
我认为这将有泄漏的话,我们将使用:
I think it would have the leak if we will use:
static BackGroundWorker bgWorker;
来代替:
BackGroundWorker bgWorker;
这篇关于内存泄漏:用Java垃圾收集之间的混淆 - 和Android杀害机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!