Working of Garbage Collector

Source: Internet
Author: User

From http://www.c-sharpcorner.com/UploadFile/udeshikah/009012008004745AM/0.aspx

In this article I will give you an introduction of how C # garbage collector works.

In shortly I can introduce garbage collector as a worker which runs on separate thread and keeps the developer away by the memory management of the program.

Basically it gives two advantages to the programmers

    1. Programmers can mainly focus on the logic of the program â € "In early versions ages such as unmanaged C ++ programmers have to spend lot of their development effort on this memory management, even for well experienced programmers.
    2. Second one is it helps to keep integrity of the program, if u have ever used unmanaged C ++ you may experienced, how many times trying to de allocate memory of object which is already de-allocated. i'm sure at least once

So garbage collector keeps you away by this burden of memory management. By the way it can do the job perfectly.

So if the Garbage Collector doing it's job perfectly, how is it?

To answer this question you must first understand the way memory is used by the C # program. Basically there are two parts in the memory, called Stack and heap.

You must know few things about Stack

Stack is :-

    1. Is considerably small and keeps the references to the heap objects.
    2. Each new thread creates new stack frame.
    3. Value types (structs in C #-usually 16 bytes or less) are used to live in the stack.
    4. Faster in accessing stack elements.

Heap is :-

    1. Large memory area and all the objects (reference types) used to live in the heap.
    2. You can not directly access the elements in heap without any reference from the stack.

Garbage Collector Algorithm

Each thread use to create new stack in the memory, as I told abve this stack contains the pointers to the objects in the heap. this pointer refers to an object in the heap or it is null. (if we tried to access NULL pointer it throws nullreferenceexception in. net Framework)

So now we will move on to garbage collection algorithm. When garbage collection starts it assumes that all objects in the heap are as garbage.

Then Garbage Collector achieves its goal by three phases:

Phase 1: Examine phase

In this phase Garbage Collector identify roots by examine the thread stack. What are these roots in our C # class?

Usually

    1. Static Fields
    2. Method Parameters
    3. Local Variables
    4. CPU registers

These four types can be identified as roots in our class.

Keep in mind that value types are never become roots, because as I told above they used to live in the stack and destroys when stack blows.

Phase 2: marking phase

During this phase what garbage collector doing is when it is moving through the thread stack while identifying the roots, if it finds out that root refers to an object in the heap (this means the object is accessible to the outside world) marks it.

Marking is done by turning on the sync block of the each object.

Another thing must be remember here is one object can refers to another object by inside itself. In this scenario marking the first object caused to mark the second one as well.

Let's consider this scenario,

Class Obj1{}

 

Class Obj2

{

Static Obj1A;

 

Static VoidMain (){

A =New Obj1();

}

}

In this simple example we can see class obj2 internally refers to the obj1.what is inside Memory does can be shown in a dimo-this way

So simply what happens when garbage collection occurs is marking obj1 causes to mark obj2 as well, as I told above.

Finally all unreachable objects (unmarked objects) are considered as garbage, and the memory occupied by them can be reclaimed back. In the above example obj3 and obj5 memory can be reclaimed to the user.

Phase 3: Compact phase

This is final phase of one collection cycle. after reclaiming the unmarked objects memory now there is only the non-garbage objects in the memory. so in this phase Garbage Collector shfits those objects down the memory, and moves the next-object-pointer to the next free memory Loacation (when you create another object using new keyword in C # That object places here and moves the next-object-pointer ahead, when ever if there is no enough space available new throws outofmemoryexception ).

Although I have discussed. NET Framework garabage collection Algorithm in shortly, there are some more things to discuss such as what happens when we include finalizers in our classes definition? When to use or not finalizers?

One thing you must remember is. net garbage collector is well written and well tuned at the same time it is self-tuninng tool (later I will discuss about generations and self-tunnig of Garbage Collector ). so it is always better to let the Garbage Collector to do it's duty himself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.