Site Feed

Wednesday, October 27, 2004

Garbage Collection

Garbage collection is a mechanism by which the CLR reclaims inaccessible (or unreachable) memory allocated to an object. Question, when does an object become unreachable? This can be determined by the references that an application has to this object at any given point of time. This can happen in different ways. An object can go out of scope or if the reference to an object can be explicitly set to null rendering the references to be invalid. Thus, the Garbage Collector has to keep a track of all objects that needs to be garbage collected.

How does this happen? Let me start by asking to when do the GC first gets invoked? The GC first gets invoked as soon as the first object for the application gets generated on the heap when starting. Once started, the garbage collection process runs on a thread that is separate from the application main thread. This thread is completely inaccessible to the main thread in the application thus providing complete security to the garbage collection thread. Every time an object is allocated a memory space using the new key word, the garbage collection runs.

When the garbage collection runs, it first mark all the objects created in the memory to be garbage collected. Then it looks out for the references that are still alive on the object. It examines the references on an object and if found, it de-marks the object. Then the garbage collector reclaims all memory which was allocated to objects that are no more referenced in the managed code. This process is called mark-and-sweep.