Garbage collection in

How Garbage Collector(GC) works?

How Garbage Collector (GC) works?
Microsoft .NET CLR environment provides automatic memory management using Garbage Collection (GC). Garbage Collection (GC) basically a process that frees or releases the object from the memory which is no longer is in use by program. When we create new object Common Language Runtime (CLR) allocates the memory to new object on managed heap. Till the time memory has free space runtime allocates it to a new object but when memory gets full Garbage Collection comes into the picture. Garbage Collection GC basically performs memory clean up in order to make space available for other newly created object.

Benefits of Garbage Collections are that it allows us to develop application without implementing logic to free memory. Also it allocates objects on memory very efficiently. It reclaims the objects those are no longer in use and frees the memory for new objects to be allocated. Also provides safe memory operations by making sure that one object cannot use other object

When Garbage collection(GC) Occurs or run?

Garbage collection happens for below conditions.
  • If system has low memory
  • If the memory allocated to object exceeds.
  •  if GC.Collect get called.
How Garbage Collector(GC) keep track of object's life?
The heap is organized in generations so that it can keep track of short time spaned object and long time spaned objects i.e. (short-lived and long lived objects). Garbage collection occures for short time spaned object who occupies small part of heap. There are three types of generations on the heap:

  • Gen 0
              It contains short spaned objects.GC collection mostly happen in Gen0. Newly allocated object are  implicitly comes under Gen0 if object is not a large object. Example: Temp variables or local variables to the process.
  • Gen 1
             It is buffer between short spaned object memory and long spaned object memory. if Gen0  space is not enough for newly allocated object then data moved to Gen1.
  • Gen 2
           It contains objects with long span and going to be used for long period. Example: global variables those are going to be used through out the applicaion life.

How to clear unmanaged resources?
Unmanaged resources are the resources that does not taking care by CLR. Means those are not cleared from memory using Garbage Colletion(GC). File system object, database connection objects, windows handlers...etc are the examples of unmanaged resources.
We can use both implicit and explicit way to free such unmanages resources. Implicit way is to implement Finalize Method on an object. GC (Garbage Collector) calls this method when object is no longer referenced.

Explicit way is to implement  IDisposable Interface and it's  Dispose method.


Post a Comment