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
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.
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.