In Android I have singleton class but I am not sure if the garbage Collector can deallocate it.
If garbage Collector will deallocate my singleton class how can avoid it from deallocation?
In Android I have singleton class but I am not sure if the garbage Collector can deallocate it.
If garbage Collector will deallocate my singleton class how can avoid it from deallocation?
Garbage collection collects objects that nothing is pointed to, unless a reference is static. Are static fields open for garbage collection?
The only reason gc will dealocate your instance is if the entire app is destroyed...
static { new Object(); }
That is a singleton and it is garbage collected instantly. –
Lamasery There are lots of ways to implement a Singleton. One of the best is:
public static enum My { SINGLETON; }
Whether or not something is a singleton has no bearing on whether it is GCed or not. An object will be GCed if there are no Strong references to it. Look it up (http://weblogs.java.net/blog/2006/05/04/understanding-weak-references).
There is one more issue that is of interest. In Android, your application does not control it's lifecycle. It is possible that a process will be terminated and re-created in ways you do not expect. If that happens, static final variables will be re-initialized. There's more on that here:
http://portabledroid.wordpress.com/2012/05/04/singletons-in-android/
© 2022 - 2024 — McMap. All rights reserved.