Reputation: 1380
I simple question but maybe a complex content. For example, I have this classes:
Singleton is a singleton class pattern, for example:
public class Singleton {
static Singleton instance = new Singleton();
private Singleton();
List<HeavyObject> listaObjects;
}
I use this Singleton in any context (Activity).
My question is: Can Android release this class in any moment without release the current Activity? i.e., I'm watching Activity B, can Android destroy (release) my class Singleton or are the classes only unloaded when all the app is released?
Or maybe when an Activity is destroyed, because the classes are in the context of the Activities?
Upvotes: 1
Views: 1554
Reputation: 14751
I'm assuming your Singleton.instance is in fact a static field (otherwise your example doesn't make much sense).
In that case, your Singleton lifetime will be tied to the lifetime of your application's process. The process lifetime starts when the first Activity of the process is invoked (or a call made to a service that the process implements.)
The process may be destroyed at any time after all the processes Activity's are stopped.
So if you have an Activity that is not stopped, the instance will remain. But if all the Activity's in your process are stopped, the process can be destroyed at any time. If your Activity gets started again, if the process has been destroyed in the meantime, the instance will have to be created again.
Upvotes: 1
Reputation: 36449
If there are no outstanding references to Singleton, as in any references are null, the garbage collection mechanism will destroy it once it does its rounds. This means that it will most likely be destroyed but not instantaneously once all references are null.
However, if even one Activity is using Singleton, it won't be released unless that Activity is destroyed
Upvotes: 1