Can garbage Collector deallocate singleton instance? (and why or how to avoid it)
Asked Answered
C

3

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?

Consensual answered 2/3, 2013 at 16:6 Comment(1)
There is convention of using WeakReference, try to use that.Leoraleos
O
3

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

Outleap answered 2/3, 2013 at 16:10 Comment(3)
There is no such thing, in Java, as a "static object".Lamasery
An object's structure cannot be declared static, but you can have a static reference/instance of it. Answer edited to say reference.Outleap
Yeah! I think, though, that you could just leave out the whole thing about static references. Your answer is complete and correct, at the comma!Lamasery
W
2

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

Warfore answered 2/3, 2013 at 16:8 Comment(1)
This is patently false: Consider: static { new Object(); } That is a singleton and it is garbage collected instantly.Lamasery
L
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/

Lamasery answered 2/3, 2013 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.