This is an attempt to understand garbage collection.
When an object becomes a garbage, it needs to be removed from the system. It is like how we have some items which are no longer required and we throw it in the dustbin.
Can we garbage collect Singleton objects from the system?
Technically speaking, when does an object become a garbage? Can Singleton object be ever garbage collected? Even if some Singleton’s are no longer referenced by the application, should it be cleaned up?
Suppose we do cleanup the Singleton object. What are the consequences? Probably, when the Singleton was being referenced, there was some state captured about the system. And this state could be of use later on. If this state is lost, then system would lose this crucial piece of information for it’s processing. Probably someone can say that the state can be serialized so that, on next instantiation of the Singleton object, the deserialization could happen and Singleton object is updated with that state.
I need to find out what is currently being done to Singleton, when it is no longer referenced. Basically what is the object graph, where it wouldn’t be attached, inorder to be cleaned up.
We need to remember that Singleton object is constructed using static fields.
I just found out that static variables are GC roots. Since GC roots are always referencable, they will not be garbage collected. Again, we have a but. But if the classloader which loaded the Singleton class becomes eligible for garbage collection, then Singleton object becomes eligible for garbage collection.
Some useful links which are related to this topic: