Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 646
Rooban Ponraj A Avatar asked Mar 02 '13 16:03

Rooban Ponraj A


People also ask

How to avoid garbage collection?

The canonicalization techniques I’ve discussed are one way to avoid garbage collection: fewer objects means less to garbage-collect.

What is automatic garbage collection in C++?

Automatic garbage collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. An in-use object, or a referenced object, means that some part of your program still maintains a pointer to that object.

What are the advantages and disadvantages of garbage collection in Java?

The advantages of Garbage Collection in Java are: It makes java memory-efficient because the garbage collector removes the unreferenced objects from heap memory. It is automatically done by the garbage collector (a part of JVM), so we don’t need extra effort.

What is a garbage collector (GC)?

A garbage collector (GC) is a memory manager. Many programming languages have a built-in GC. This feature automatically allocates and deallocates the memory in a program. It releases tied-up, unused memory that slows down your application. The beauty of a GC is that it releases memory on your behalf, without you needing to do anything.


2 Answers

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

like image 147
Shellum Avatar answered Nov 14 '22 22:11

Shellum


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/

like image 40
G. Blake Meike Avatar answered Nov 14 '22 23:11

G. Blake Meike