Tuesday, December 14, 2010

Garbage Collector

Overview:

This article gives the brief introduction of Garbage Collector, Generations in the heap memory, Phases of Garbage collection, destructor and the benefits of Garbage collector.

Garbage Collector:
Garbage Collector was invented by John McCarthy around 1959.
Garbage Collector in .NET Framework manages the allocation and releases the memory for the application.
To the new objects created, CLR (Common language runtime) allocates space in the managed heap as long as the space is available in the managed heap. But the size of heap is limited and all allocations done on heap must be de allocated. So, based upon the allocations being made, garbage collector gets activated to release some memory.
Before reclaiming the memory, garbage collector checks whether the objects in the heap are unreferenced. Only when the objects are no longer being used, it performs its operations.



In the above figure as Data 2 is unreferenced, it is ready for garbage collection.
Except the thread that triggered the garbage collection, all the managed threads are suspended before a garbage collection starts.

Garbage Collection:
To optimize the work of garbage collector, Microsoft has divided the heap memory into three equal parts called Generations. They are GEN0, GEN1, GEN2.This is compact garbage collection. New objects are always created in GEN0 and are promoted to other generations based on their lifespan. Long lived objects would be destroyed last as these objects would move from GEN0 to GEN1 and from GEN1 to GEN2.
In .Net the address of object can change at runtime as it goes from one generation to another.
The object once created are never guaranteed to be destroyed because they might get promoted in higher generations and garbage collector would not visit those generations as memory is mostly available in lower generations itself.



Conditions for a Garbage Collection:
Only when one of the following conditions is true, garbage collection occurs:
· If the physical memory of system is low.
· On the managed heap, if the threshold of acceptable memory usage exceeded.
· If the GC.Collect () is called. This method is rarely used because the garbage collector runs continuously.
The Garbage collector can be forced at a certain point in the code by calling System.GC.Collect (). System .GC class is a class which represents the garbage collector, and Collect () method initiates a garbage collection.

Garbage Collection Phases:
Every application in .net has set of roots known as Application roots. The storage locations are being identified by these roots, which refer to objects on the managed heap or to the unreferenced objects.

The Phases in Garbage collection are:
· Marking Phase: Find and creates list of all live objects or application roots.
· Relocating Phase: Updates the references to the objects that will be compacted.
· Compact Phase: Reclaims the space occupied by the dead objects and compacts the surviving objects.

Destructor:
Destructor of a class in .Net is mainly used for destroying COM objects which are created by it in unmanaged heap. Unmanaged heap is not managed by garbage collector.
A destructor is used to release the resources that an object is holding, when an object is ready to be destroyed Finalize method / Destructor is called on that object.

VB

C#(A destructor in C# cannot have any specific modifiers))

Protected Overrides Sub Finalize()

End Sub

~()

{}



Because it’s not predictable when the Destructor method is going to be executed, it’s not recommended to only rely on destructor for releasing of resources and thus Microsoft has suggested two methods that can be invoked by the programmer for the release of resources
1. Close()
2. Dispose()
If any of these methods are invoked by the programmer before losing the reference to an object, care must be taken to avoid Finalize() method to be invoked on the same object when it is garbage collected and that can be done using GC.SuppressFinalize().
Syntax:
Public sub Dispose () or Close ()
-------Code to release resources--------
GC.SuppressFinalize (Me)
End Sub
In VB.Net only the above mentioned form of Finalize is treated as Destructor. There are multiple overloaded forms of Finalize but the other forms are not treated as destructors.
Close() or dispose() methods are custom methods and hence they have to be explicitly called just before unreferencing an object is done. Whereas destructor is automatically called when the object is destroyed by Garbage Collector.

Benefits:
· Without having to free memory, it enables to develop the application.
· In the Managed heap, objects are allocated memory efficiently.
· Clears the memory of unreferenced objects and keeps the memory available for future allocations.
· Memory safety is being provided making sure that one object cannot use the content of another object.

Summary:
Garbage collection in the Microsoft .NET common language runtime environment manages the allocation and releases the memory for application. It gets activated when the managed heap is full and there is need for release of memory. Before GC performs its action it checks whether the object is unreferenced.
Unmanaged heap is not managed by garbage collector. Destructor of a class in .Net is mainly used for destroying COM objects which are created by it in unmanaged heap.

Order of Exceptions

Order of Catch blocks is very importent while implementing the Catch Blocks.For Example if my code is expected to throw DivideByZeroException , If you know the exception type properly you have to write the specifice expected exception then write generic exception. See below example
Ex:
public class Mathematics
{
public int DivisionResult(int x, int y)
{
try
{
return x / y;
}
catch (DivideByZeroException de)
{
return -0;
}
catch (Exception)
{
return -1;
}
}
}


Note1: In the above example if you change the order of Catch you will get compile time error “A previous catch clause already catches all exceptions of this are of a super type (‘System.Exception’)”. This is because of all the exceptions can be caught by the generic catchblock.
Note2: How many catch blocks can i have for a single try block . Answer is no limit.
Note3 : Can i have a try without a catch. Ans: a try should always either have a catch or finally. try will never exist alone ( try cannot be a bachelor ).

Tuesday, December 7, 2010

STATIC in C# .NET

In C#, whenever you declare a variable which is bound to an instance (object) of a class, your variable by default gets its own copy of all the fields in the class. So for example, if you write:

CreditCardAccountPremium cp1 = new CreditCardAccountPremium();
CreditCardAccountPremium cp2 = new CreditCardAccountPremium();
cp1.setFirstName("George");
cp2.setFirstName("Harry");

-- the instances cp1 and cp2 each contain their own string called FirstName. Changing the FirstName in cp2 has no effect on the value of the FirstName in cp1. However, there are some cases where you do not want this behavior. Maybe you would like to set a maximum value for a CashAdvance that is common to the entire CreditCardAccountPremium class. This would be universally applied to all instances of CreditCardAccountPremium.

We really want the "maxCashAdvance" to be stored in memory only once, no matter how many instances of the class we instantiate. To do this, we place the keyword static before the field declaration:

public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
....


Fields declared with the static keyword are referred to as static fields or static data., while the other fields like FirstName are called instance fields. So an instance field belongs to an object, and a static field belongs to the class as a whole. Static fields exist from the moment the assembly containing the class is loaded, and are initialized by the runtime, independent of whether you actually declare any instances of the class. Consequently, we can also have static constructors, which serve no other purpose than to assign initial values to static data:

public class CreditCardAccountSuper
{
private static uint maxCashAdvance;
staticCreditCardAccountSuper()
{
maxCashAdvance = 300;
}


If you were to invoke a CreditCardAccountSuper.maxCashAdvance property, there is no need to assign an initial value within the Main() method; the static constructor does this automatically. Note that the static constructor in which the maxCashAdvance default value is set has the same name as the class, and cannot take any arguments.

Just as is the case with fields, you can declare methods as static provided they don't try to access instance data or any other instance methods. You might want to provide a method to allow users of the class to view the maxCashAdvance value:

public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;

public static uint GetMaxCashAdvance()
{
return maxCashAdvance;
}


You access static methods and fields associated with a class differently that you access them as objects (instances of a class). Instead of specifying the name of the instance to access the method (cp1.GetMaxCashAdvance) you will specify the name of the class: CreditCardAccountPremium.GetMaxCashAdvance(). The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types. C# trashes the whole concept of global functions, variables, and constants. Instead, you can create static class members, making your C# code not only easier to read, but less likely to cause naming and other conflicts.

source:eggheadcafe

More on Static Class

http://www.c-sharpcorner.com/UploadFile/4d790c/5736/