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?

Chiel ten Brinke
  • 12,091
  • 12
  • 60
  • 104
Rooban Ponraj A
  • 281
  • 4
  • 19

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,059
  • 2
  • 18
  • 26
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,323
  • 3
  • 21
  • 38
1

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

Chen Kinnrot
  • 19,385
  • 15
  • 74
  • 132