Showing posts with label Garbage Collection. Show all posts
Showing posts with label Garbage Collection. Show all posts

Tuesday, July 2, 2013

Garbage Collection

Concept of Garbage Collection

When Microsoft planned to go for a new generation platform called .NET with the new generation language called C#, their first intention is to make a language which is developer friendly to learn and use it with having rich set of APIs to support end users as well. So they put a great thought in Garbage Collection and come out with this model of automatic garbage collection in .NET.

They implemented garbage collector as a separate thread. This thread will be running always at the back end. Some of us may think, running a separate thread will make extra overhead. Yes. It is right. That is why the garbage collector thread is given the lowest priority. But when system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time), then garbage collector thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.


What is Garbage Collection...

The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. As long as address space is available in the managed heap, the runtime continues to allocate space for new objects. However, memory is not infinite. Eventually the garbage collector must perform a collection in order to free some memory. The garbage collector's optimizing engine determines the best time to perform a collection, based upon the allocations being made. When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.


class First
{
~First()
{
System.Diagnostics.Trace.WriteLine("First's destructor is called.");
}
}

class Second : First
{
~Second()
{
System.Diagnostics.Trace.WriteLine("Second's destructor is called.");
}
}

class Third : Second
{
~Third()
{
System.Diagnostics.Trace.WriteLine("Third's destructor is called.");
}
}

class TestDestructors
{
static void Main()
{
Third t = new Third();
}

}
/* Output (to VS Output Window):
Third's destructor is called.
Second's destructor is called.
First's destructor is called.
*/


class mind
{
~mind()
{

}

public static void Main()
{

}

}
//The destructor implicitly calls Finalize on the base class of the object. Therefore, the previous destructor code is implicitly translated to the following code:

Copy
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}

Tuesday, March 12, 2013

what is Dispose and Finalize in .net


Introduction

We have been using the Dispose method for disposing objects in .NET. For the same purpose, we may also use the Finalize method. In this article I will try to explain what the Dispose and the Finalize methods are and where to use the Finalize and where to use the Dispose. I will also try to explain the difference between them.

Dispose
Garbage collector (GC) plays the main and important role in .NET for memory management so programmer can focus on the application functionality. Garbage collector is responsible for releasing the memory (objects) that is not being used by the application. But GC has limitation that, it can reclaim or release only memory which is used by managed resources. There are a couple of resources which GC is not able to release as it doesn't have information that, how to claim memory from those resources like File handlers, window handlers, network sockets, database connections etc. If your application these resources than it's programs responsibility to release unmanaged resources.

For example, if we open a file in our program and not closed it after processing than that file will not be available for other operation or it is being used by other application than they can not open or modify that file. For this purpose FileStream class provides Dispose method. We must call this method after file processing finished. Otherwise it will through exception Access Denied or file is being used by other program.

Close Vs Dispose

Some objects expose Close and Dispose two methods. For Stream classes both serve the same purpose. Dispose method calls Close method inside.

void Dispose() 

this.Close(); 
}

Here question comes, why do we need Dispose method in Stream. Having Dispose method will enable you to write below code and implicitly call dispose method and ultimately will call Close method.

using (FileStream file = new FileStream("path", FileMode.Open, FileAccess.Read)) 

//Do something with file 

 
But for some classes both methods behave slightly different. For example Connection class. If Close method is called than it will disconnect with database and release all resources being used by the connection object and Open method will reconnect it again with database without reinitializing the connection object. However Dispose method completely release the connection object and cannot be reopen just calling Open method. We will have re-initialize the Connection object.

Creating Dispose
To implement Dispose method for your custom class, you need to implement IDisposableinterface. IDisposable interface expose Dispose method where code to release unmanaged resource will be written.

Finalize

Finalize method also called destructor to the class. Finalize method can not be called explicitly in the code. Only Garbage collector can call the the Finalize when object become inaccessible. Finalize method cannot be implemented directly it can only be implement via declaring destructor. Following class illustrate, how to declare destructor. It is recommend that implement Finalize and Dispose method together if you need to implement Finalize method. After compilation destructor becomes Finalize method.

public class MyClass:IDisposable 
{
//Construcotr 
public MyClass() 

//Initialization: 
}
//Destrucor also called Finalize 
~MyClass() 

this.Dispose(); 
}
public void Dispose() 

//write code to release unmanaged resource. 

}

Using Finalize

Now question is, When to implement Finalize? There may be any unmanaged resource for example file stream declared at class level. We may not be knowing what stage or which step should be appropriate to close the file. This object is being use at many places in the application. So in this scenario Finalize can be appropriate location where unmanaged resource can be released. It means, clean the memory acquired by the unmanaged resource as soon as object is inaccessible to application.

Finalize is bit expensive to use. It doesn't clean the memory immediately. When application runs, Garbage collector maintains a separate queue/array when it adds all object which has finalized implemented. Other term GC knows which object has Finalize implemented. When the object is ready to claim memory, Garbage Collector call finalize method for that object and remove from the collection. In this process it just clean the memory that used by unmanaged resource. Memory used by managed resource still in heap as inaccessible reference. That memory release, whenever Garbage Collector run next time. Due to finalize method GC will not clear entire memory associated with object in fist attempt.

Conclusion

It is always recommended that, one should not implement the Finalize method until it is extremely necessary. First priority should always be to implement the Dispose method and clean unmanaged as soon as possible when processing finish with that.

Friday, September 28, 2012

Difference between Dispose and Finalize


Dispose and Finalize in C#

Introduction

This article provides an introduction to destructors in C# and reveals the non-deterministic destructor problem.
It also analyzes the IDisposable, garbage collection, using statement, etc.
Destructor
The destructor is a special purpose method in a class like a constructor. The constructor is called by the runtime after creating an instance. It is meant for initialization purposes. Like that, a destructor is called by the runtime before destroying an instance. It is meant for finalization operations.
A destructor is declared like a constructor with a prefix tilde(~) in C#. A destructor do not have access modifiers like publicprivate, etc.
public class Shape
{
    ~Shape() // Destructor
    {
    }
}
In C#, the .NET runtime automatically destroys any class instances that are no longer in reference. It does this during the process of garbage collection.
Using of destructors will make the application slow in performance.
Finalizers
It is important to note that the destructors are also called Finalizers because the compiler converts a C# destructor into a method named Finalize() in the Intermediate Language (IL). The code in the destructor will be wrapped in a try..finally block inside the Finalize() method.

Garbage Collection
This is the process of freeing up of unused memory of objects periodically. The .NET runtime does the process of garbage collection on the following conditions:
  • When there is shortage of memory
  • Developer invoked the GC.Collect() method
The garbage collection helps the developer to free up object instances.
But remember, garbage collection only destroys the managed resources, i.e. resources created inside the managed memory.
What is the Need of Destructors?
Since the runtime is managing the destruction of all objects, a question may arise: Why do we need destructors?
Answer: To destroy unmanaged resources.
The unmanaged resources are those created outside the managed environment. They may include file handles, network connections, etc. These resources created should be destroyed by the class itself, because the runtime is not able to destroy them.



Therefore, we use destructors to free up the unmanaged resources. This will ensure that all the unmanaged resources created by the class will be freed in the destructor.
E.g.: Let Channel be a class using unmanaged resources having a constructor and a destructor.
public class Channel
{
    public Channel()
    {
        // Create unmanaged resource
        // Lock("c:\\file.log");

    }

    ~Channel()
    {
        // Destroy unmanaged resource
        // Unlock("c:\\file.log");

    }
}
The Channel class locks a file "c:\file.log" in the constructor and unlocks it in the destructor.
Here arises a problem that we cannot predict when the destructor is called. So the file remains locked until the garbage collection, even if the object instance is out of any reference.
For the above problem, we need some method to free the unmanaged resource. In .NET, there is an interface named IDisposable for the purpose.
IDisposable
The IDisposable interface contains a method Dispose() which should be implemented by the class. So we can move freeing up of unmanaged resources to this Dispose() method.
Again there is a problem, that a typical .NET developer not calling the Dispose() method after the usage of class instance. In that case, we need the call to free unmanaged resources both in the destructor and in the Dispose() method.
We can also use a Close() method instead of implementing the IDisposable interface. But, enabling the IDisposable makes our class usable in the using {}statement of C#.
The using statement will automatically call the Dispose() method after exiting the scope of using. (Please refer to the sample code.)
public class Channel : IDisposable
{
    public Channel()
    {
        // Create unmanaged resource
        Lock("c:\\file.log");
    }
    ~Channel()
    {
        // Destroy unmanaged resource
        Unlock("c:\\file.log");
    }
    void IDisposable.Dispose()
    {
        Unlock("c:\\file.log");
    }
    public void Lock(string file) { }
    public void Unlock(string file) { }
}
At first look, the above code solves all the problems.
But, it creates a new problem due to the non-deterministic destructors of C#.
Non-Deterministic Destructors
In C#, we do not know when the destructor is executed. It is called only during the garbage collection process and we do not know when it actually happens. This state is called non-deterministic destructors or InDeterministic destructors.
The following figure illustrates the problem. Our 'Channel' class is using some unmanaged resources and freeing them in the Dispose() method and also in the destructor.
There are two cases when the Channel class is used:
  1. A developer creates an instance and exits without calling Dispose()
  2. A developer creates an instance and calls Dispose() 

Solution using GC.SuppressFinalize(this)
We can instruct the garbage collector not to call the destructor by using the GC.SuppressFinalize(this) method. So, using this in the Dispose() method after freeing up unmanaged resources will solve the non-deterministic destructor problem.
The solution is given below.
Here, the Channel class has freed up code both in the destructor and in the Dispose() method. And if the developer calls the Dispose() method, the unmanaged resources will be freed and the destructor will be disabled by using GC.SuppressFinalize(this);.
If the developer does not call the Dispose() method, the unmanaged resources are freed up in the destructor by the garbage collector. The figure below illustrates the solution:

Note: The Dispose() method is used to free up the unmanaged resources, and calling Dispose() will not free up the instance. It just executes whatever statements are written in it.
Using the Code
The code along with this article demonstrates the case of using/not using Dispose(), and also the initiating of the GarbageCollection process using GC.Collect(). Please analyze the Channel class to see the details involved.