The garbage collector releases resources and memory for objects stored on the heap.
The garbage collector runs in its own thread and normally runs automatically, under well-defined circumstances. When the garbage collector runs, other threads in an application are halted because the garbage collector may move objects in memory and must update pointers to the correct addresses for these objects.
The garbage collector takes the following steps to reclaim resources:
- It marks every object as dead; objects are considered dead unless proved otherwise.
- It starts from objects referenced on the stack, marking referenced objects as alive. It performs this recursively; if an object that is already marked as alive references another object, that object is also marked as alive. The garbage collector includes logic to prevent infinite recursion, for example, where there is a circular reference between two objects.
- It checks whether any of the objects that have been marked as dead have a destructor that must be run. Running the destructor is referred to as finalization. Any objects that require finalization are moved to a data structure maintained by the garbage collector called the freachable queue. The freachable queue stores pointers to objects that require finalization before their resources can be reclaimed.
- Objects added to the freachable queue are marked as alive because there is now a valid reference to them; the destructor must be run before their memory can be reclaimed. Objects are normally added to the freachable queue only once.
- Objects marked as alive are moved down the heap to form a contiguous block, defragmenting the heap. References to objects (on the stack and in other objects on the heap) moved by the garbage collector are updated.
- Other threads resume.
- On a separate thread, objects added to the freachable queue are finalized. After an object is finalized, the pointer to that object is removed from the freachable queue. Objects are not removed from memory until the next time the garbage collector runs.
You can download this video to understand this …