Thursday, February 10, 2011

Constructors, Destructors and Finalizers

The syntax and semantics for constructors in C# is identical to that in Java. C# also has the concept of destructors which use syntax similar to C++ destructor syntax but have the mostly the same semantics as Java finalizers. Although finalizers exist doing work within them is not encouraged for a number of reasons including the fact that there is no way to control the order of finalization which can lead to interesting problems if objects that hold references to each other are finalized out of order. Finalization also causes more overhead because objects with finalizers aren't removed after the garbage collection thread runs but instead are eliminated after the finalization thread runs which means they have to be maintained in the system longer than objects without finalizers. Below are equivalent examples in C# and Java.
NOTE: In C#, destructors(finalizers) automatically call the base class finalizer after executing which is not the case in Java.
C# Code
using System;

public class MyClass {

static int num_created = 0;
int i = 0;

MyClass(){
i = ++num_created;
Console.WriteLine("Created object #" + i);
}

~MyClass(){
Console.WriteLine("Object #" + i + " is being finalized");
}

public static void Main(string[] args){

for(int i=0; i < 10000; i++)
new MyClass();

}

}

Java Code
public class MyClass {

static int num_created = 0;
int i = 0;

MyClass(){
i = ++num_created;
System.out.println("Created object #" + i);
}

public void finalize(){
System.out.println("Object #" + i + " is being finalized");
}

public static void main(String[] args){

for(int i=0; i < 10000; i++)
new MyClass();

}

}

No comments:

Post a Comment