Tuesday, January 10, 2012

Programmatically Garbage Collection - Generation

- Suresh Pitchi
Hope most of us know that what garbage collection is. But, how many people of us know how it works and how the CLR manage allocated class instance via garbage collection?. First we will explain programmatically how garbage collection is implemented, using System.GC class type are explained below and how object will be stored on Heap and Stack.
Object stored in Heap and Stack.
Take the example below, how the call reference from heap and stack
 public class GenerationObectExample
 {
   public int id { get; set; }
   public string name { get; set; }
   public GenerationObectExample();
   string GeneationMethod()
   {
    return "Gereation objection";
   }
 }
class garbage
{
   void CallGarbageCollector()
  {
   Console.WriteLine(“print out generation”);
   //Object stored on the heap
   GenerationObectExample myobject = new    
    GenerationObectExample();
   //object stored in reference
   myobject.GeneationMethod();
  }
}
Once the Class is defined it can be allocated with any number of objects using C# new keyword. The “new” keyword returns a reference to the object on the heap not on the actual object. If we declare the local variable in the method, it will store in the stack. When we invoke the member on the object using the C# dot or period operator, the reference are stored for the object. Structures are value type that are always allocated on the stack and never place on the .NET managed heap. Heap are allocated only when you are creating instance of class.
Object Lifetime.
In C# application within the .NET runtime environment it will take care of managed heap without direct intervention of it. Now we are going to know how the Garbage Collector destroys the object. Garbage collector removes the object from heap, once it is unreachable by any part of code.
     void GenerationMethod()
 {
   //it will distoryed when the method return the value
   Generationobject myObeject = new     
    Generationobject("genrationZero""generationOne");
   myObeject.GenerationMethod();
 }
Take the above example, when the method returns the value, the Garbage Collector start working to clear the object. But, how it will work. It is like Generation concept. The idea behind generation is simple. The Generation has three stages.
Generation 0, Generation 1, Generation 2.
Generation 0 : Identifies a new allocation object that is, when application create fresh object that are marked as Generation 0. In this stage GC clear the object from heap.
Generation 1 : Identifies an object that has survived a garbage collection. In this stage, GC that is not able to clear from Generation 0 will be moved to Generation 1.
Generation 2 : Identifies an object that has survived more than one sweep of the garbage collection. In this stage, what exactly happen, when GC cannot clear object in generation 0 and 1, it move then gen2. GC spent more time on Generation 0 rather than Generation 1 and Generation 2.
Here the example explain how to generation move to stage by stage.
class GarbageCollection
{
 static void Main(string[] args)
 {
  //print out estimatied nunber of bytes on heap
  Console.WriteLine("\nEstimatied number of bytes on heap : {0}",
        GC.GetTotalMemory(false));
       
  //Max Generation is zero based
  Console.WriteLine("\nThis OS has {0} object generation.\n",
         GC.MaxGeneration);
       
  //print out generation of Generationobject class
  Generationobject objectGeneration=new
  Generationobject("genrationZero","generationOne");
  Console.WriteLine("\n", objectGeneration.ToString());
  Console.WriteLine("\nPrint out GENERATION of Generationobject :    
   {0}",
  GC.GetGeneration(objectGeneration));
      
  //make the ton of object is testing purpose
  object[] tonsofObject=new object[50000];
  for(int i=0;i<50000;i++)
   {
     tonsofObject[i]=new object();
   }
  
//collect only generation 0 object
  GC.Collect(0,GCCollectionMode.Forced);
  GC.WaitForPendingFinalizers();

  //print out the generation of refer Generationobject class
  Console.WriteLine("\nGENERATION of refer Generationobject class 
   is : {0}",
  GC.GetGeneration(objectGeneration));
  //see the tonofobject[9000] is still alive
  if (tonsofObject[9000] != null)
   {
     Console.WriteLine("See the tonof object[9000] is still alive 
      :{0}",
     GC.GetGeneration(tonsofObject[9000]));
   }
  else
   {
     Console.WriteLine("Tonofobject[9000] is no longer alive");
   }

  //print out how many time a generation has been swept
  Console.WriteLine("\nGENERATION 0 has been swept {0}
    times",GC.CollectionCount(0));
  Console.WriteLine("\nGENERATION 1 has been swept {0}
    times",GC.CollectionCount(1));
  Console.WriteLine("\nGENERATION 2 has been swept {0}
    times",GC.CollectionCount(2));
  Console.ReadLine();
  }
}

Output :


The above example explain how to sweep the generation from one stage to another stage of Generationobject class. The GC swept two time from Generation 0 and one time from Generation 1.
So here this is some basic understanding know of how the Garbage collection works internally from the .NET perspective.  










1 comment:

Aaron Bentley said...

Awesome blog. I enjoyed reading your articles. This is truly a great read for me.I am looking forward to reading new articles. Keep up the good work.
disk doctors digital media recovery