活动举办参考辛格尔顿泄漏内存? [英] Activity holding reference to Singleton leaks memory?

查看:135
本文介绍了活动举办参考辛格尔顿泄漏内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有code是这样的:

If I have code like this:

public class MyActivity extends Activity 
{

private SingletonClass singletonInstance;

...

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    singletonInstance = SingletonClass.getInstance();
}

...
}

我的理解是,该活动将继续活着,因为它有一个静态实例的引用,因此将无法被GC'd。然而,这似乎并没有引起我在我的应用程序的任何问题。难道我不明白GC或这是真的泄漏内存,而且我应该避免保持一个参考我的单身类?

My understanding is that the Activity will remain alive because it has a reference to a static instance and therefore will fail to be GC'd. However, it doesn't seem to cause me any problems in my application. Do I not understand GC or is this really leaking memory and I should avoid keeping a reference to my singleton class?

推荐答案

有关研究之您的疑问并确认我的答案是:

Researched about your doubt and I confirm my answer:

如果您声明singletonInstance为静态它会发生。为了您的活动,singletonInstance只是SingletonClass的一个实例。请记住,有没有这样的事情作为一个静态实例,实例仅仅是一个给定的类的对象,让他静是你在你的范围内声明的方式。对于MyActivity,singletonInstance也不是一成不变的,即使里面SingletonClass你引用到同一个对象/实例,那里被声明为静态的。

It would happen if you declared singletonInstance as static. For your Activity, singletonInstance is just an instance of SingletonClass. Remember that there's no such thing as a "static instance", the instance is just an object of a given class, what makes it static is the way you declare it in your scope. For MyActivity, singletonInstance is not static, even if inside SingletonClass you're referencing to the same object/instance and there it is declared as static.

这样,你的活动可以通过GC没有问题的清理。我有在Android类似的执行,它涉及到服务,有它运行几百小时,没有任何内存或性能问题...

This way, your Activity can be cleaned up by GC without issues. I have a similar implementation on Android and it involves a Service, have had it running for hundreds of hours without any memory or performance issues...

问候

这篇关于活动举办参考辛格尔顿泄漏内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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