Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 613
Arvis Avatar asked Dec 15 '12 09:12

Arvis


People also ask

Should singleton fields be static?

The static instance variable inside of a singleton is meant to hold the only instance of the class that will exist. It is static because it will need to be referenced by a static method 'GetInstance()' that will return the instance, or will create the instance if it is the first time that 'GetInstance()' was called.

Why is singleton instance static?

The purpose of Singleton is to have only one instance of that object[1]. By making a sealed class with a private static instance which is automatically instantiated on first access, you provide its necessary trait of only creating one copy of the actual object that is then accessed by the Singleton.

Are static variables singletons?

Statics are the metter of classes --> no relation with singleton pattern.

Is Android service a singleton?

Finally, Service in Android is a singleton. There is only one instance of each service in the system.


1 Answers

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.

like image 116
Raffaele Avatar answered Oct 05 '22 20:10

Raffaele