Arvis Arvis - 23 days ago 15
Android Question

Static singleton lifetime in Android

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?

By official Android doc:


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


By some post:

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


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.


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?

Answer

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.

Comments