Garbage collector serves as a automatic memory manager. It allocates memory for objects on managed heap. The heap is divided into three generations, generation 0, generation 1 and generation 2 , so it can handle short-lived and long-lived objects. A temporary variable is an example of short-lived object and an object in server application with static data is an example of long lived object.
Generation 0 is youngest generation and contains short-lived objects. All newly created objects are contained in generation 0. Garbage collection occurs more frequently in this generation. If there is no memory in generation 0, they are promoted to generation 1.
Generation 1 acts as a buffer between short-lived and long-lived objects, it contains short-lived objects.
Generation 2 contains long lived objects.
-
A marking phase will find and create a list of all live objects.
-
A relocating phase will update the references to the objects that will be compacted.
-
A compacting phase will reclaim the space occupied by the dead objects and will compact the surviving objects. The compacting phase will move objects that have survived a garbage collection toward the older end of the segment.