Java GC compared to .Net

A question related to Java GC compared to .Net and cleaning up local references. In .Net if you run in release mode then local variables are GC'd if not in use. Can Java be compiled in a way to function the same way?

e.g C# Code

class Program

{

public Program()

{

B b =new B();

CreateA();

System.GC.Collect();

Thread.Sleep(5000);

}

privatevoid CreateA()

{

new A();

}

staticvoid Main(string[] args)

{

new Program();

}

privateclass A

{

~A()

{

Console.WriteLine("A is being GC'd");

}

};

privateclass B

{

~B()

{

Console.WriteLine("B is being GC'd");

}

};

}

In release mode, when we hit the Thread.Sleep, both A & B are Garbage collected.

In java

publicclass GCTest{

public GCTest(){

B b =new B();

createA();

System.gc();

try{

Thread.sleep(5000);

}

catch(InterruptedException e){

}

}

privatevoid createA(){

new A();

}

publicstaticvoid main(String[] args){

new GCTest();

}

privateclass A{

publicvoid finalize(){

System.out.println("A is being GC'd");

}

}

privateclass B{

publicvoid finalize(){

System.out.println("B is being GC'd");

}

}

}

When we hit the Thread.sleep only A is collected

Just something I've been wondering about,

If you can shed some light on this that'd be great.

Thanks

[3786 byte] By [LordGommosa] at [2007-11-27 9:46:39]
# 1

Hi,

why do you expect B to be collected at Thread.sleep? After all, it is still reachable over the local variable b which is on the stack until the end of the method. Ok, there are no further references to it after Thread.sleep, but this is not checked by the JVM (it only iterates over reachable objects and marks those non-garbage and afterwards collects all garbage objects). Once the execution exits the constructor method, the object will become garbage and will be collected at the next collection.

I'm not familiar with C#, so no idea how the collector works there.

Nick.

nicolasmichaela at 2007-7-12 23:57:28 > top of Java-index,Java HotSpot Virtual Machine,Specifications...