静态单身一辈子的安卓静态、单身

2023-09-04 03:07:10 作者:安若少年初入梦 °

我有一些不清楚的情况:

I have some unclear situation:

将静态单身是垃圾最后参照保持活动后收集已被破坏?因为在应用程序的更多引用到单一实例。然后我可以依靠的单身?

Will static singletons be garbage collected after last reference holding Activity has been destroyed? Because there is no more references in Application to singleton instance. Can I then rely on singletons?

官方的Andr​​oid DOC :

通常没有需要继承的应用。在大多数情况下,   静态单身可以提供相同的功能在一个更模块化   方法。

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way.

通过一些后期:

http://www.devahead.com/blog/2011/06/extending-the-android-application-class-and-dealing-with-singleton/

在开发应用程序时,我发现   势必活动,有时一些静态变量发生   即使他们已经previously被初始化未初始化!一世   认为,当一个静态变量初始化它保持这样的   该应用程序的整个生命,但是这似乎并不如此。

While developing an application, I found that sometimes some static variables bound to activities happened to be uninitialized even though they’ve previously been initialized! I thought that when a static variable is initialized it stays so for the entire life of the application, but this doesn’t seem to be the case.

在换句话说,如果不抱着一个参考我的静态单例类,什么是prevent它被垃圾收集和销毁?

In another words, if nothing is holding a reference to my static singleton class, what's to prevent it from being garbage collected and destroyed?

推荐答案

没有,因为如果它是一个单例,它存储为静态字段在同级车中,通常单身不被破坏的客户,即你不会把一个静态方法 deleteInstance()这台参考因此,如果没有人使用它,它是符合垃圾收集。对于静态字段,当它加载的类的类加载器丢弃的垃圾收集不会发生。

No, because if it's a singleton, it's stored as a static field in its class, and usually singletons are not destroyed by clients, ie you wouldn't put a static method deleteInstance() which sets the reference to null so that if nobody else uses it, it's eligible for garbage collection. For static fields, garbage collection will happen when the classloader which loaded the class is discarded.

由于这个原因,关键字静态本身可能导致内存泄漏,如果它引用的活动对象,所以你应该使用它时要非常小心。

For this reason, the keyword static itself may cause memory leaks, if it references Activity objects, so you should be very careful when using it.