I have some unclear situation:
Will static singletons be garbage collected after last reference holding Activity has been destroyed? Because there is no more referen
Yes. Every time you leave your application (for example your app opens the camera app to take a picture, or opens the browser to open a link, or the user just pushes the back button) there is a possibility that your Application
object will be destroyed and recreated when you navigate back to your app.
You should initialize any static variable in a static {}
block in your custom Application
class if you have one, or in your Activities
to ensure they won't be null.
Note that it is more probable to experience this issue on devices with weaker hardware, lower memory, but you should expect it can happen on any device.
Bottom line is, in android, don't expect that your static variables will stay in the memory at any time. Always check if they exist and reinitialize them if necessary at the right places.
EDIT:
I know it has been a long time, and I totally forgot about this thread, anyway, here is the source from the official Android lifecycle documentation:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html
You can not control when exactly Java objects become garbage collected. An object becomes eligible for garbage collection when there are no more (non-circular) references to it. With Android, further, you can not control when your Activity gets removed from memory.
singletons are supposed to represent something which always exist.
You can't force any object to be garbage collected; you can request that the garbage collector runs with System.gc() but it's only a request.
If you want to make a "singleton" eligible for garbage collection, you'd probably want to have a method to set the static variable to null (and hope that nothing else had taken a copy of the reference). Obviously the next time anyone asked for an instance, it would need to be recreated. at which point it's not really a singleton, of course.
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.
All singleton object will stay even if the activity is destroyed.