Can the garbage collector unselect one instance? (and why and how to avoid it)

In Android, I have a singleton class, but I'm not sure if the garbage collector can free it.

If the garbage collector frees my singleton class, how can I avoid freeing it?

+8
garbage-collection android singleton dealloc
source share
3 answers

Garbage collection collects objects that nothing points to if the link is not static. Are static garbage collection fields open?

+3
source share

The only reason gc will process your instance is to destroy the entire application ...

+1
source share

There are many ways to implement Singleton. One of the best:

public static enum My { SINGLETON; } 

Regardless of whether it is singleton, there is no relation to whether it is GCed or not. An object will be GCed if there are no strong references to it. Take a look ( http://weblogs.java.net/blog/2006/05/04/understanding-weak-references ).

There is another issue that is of interest. On Android, your application does not control its life cycle. It is possible that the process will be terminated and re-created in a way that you do not expect. If this happens, the static final variables will be reinitialized. There is more about this:

http://portabledroid.wordpress.com/2012/05/04/singletons-in-android/

+1
source share

All Articles