8

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?

chtenb
  • 14,924
  • 14
  • 78
  • 116
Rooban Ponraj A
  • 281
  • 4
  • 20

3 Answers3

3

Garbage collection collects objects that nothing is pointed to, unless a reference is static. Are static fields open for garbage collection?

Community
  • 1
  • 1
Shellum
  • 3,159
  • 2
  • 21
  • 26
2

The only reason gc will dealocate your instance is if the entire app is destroyed...

Chen Kinnrot
  • 20,609
  • 17
  • 79
  • 141
2

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/

G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40