Re: garbage collecton
On Sun, 21 Jun 2009 07:25:28 -0700 (PDT), asit <lipun4u@gmail.com>
wrote, quoted or indirectly quoted someone who said :
The question was when the control reaches System.gc() line, how many
objects should be eligible for CG ??
I modified your program to help you figure out what it is doing:
// explore how objects become accessible for garbage collection.
import static java.lang.System.out;
class A
{
/** id for objects */
String name;
A aob;
public A( String name )
{
this.name = name;
System.out.println("created : " + name);
}
protected void finalize()
{
System.out.println("freed : " + name);
}
public static void main(String args[])
{
A a=new A( "a" );
A b=new A( "b" );
A c=new A( "c" );
a.aob=b;
b.aob=a;
c.aob=a.aob;
// Confusing code. Don't cascade operators. You will just trip
yourself or other programmers.
A d=new A("mother").aob=new A("child");
c=b;
c.aob=null;
if ( a != null ) out.println("a: " + a.name );
if ( b != null ) out.println("b: " + b.name );
if ( c != null ) out.println("c: " + c.name );
if ( d != null ) out.println("d: " + d.name );
if ( a != null && a.aob != null ) out.println("a.aob: " +
a.aob.name );
if ( b != null && b.aob != null ) out.println("b.aob: " +
b.aob.name );
if ( c != null && c.aob != null ) out.println("c.aob: " +
c.aob.name );
if ( d != null && d.aob != null ) out.println("d.aob: " +
d.aob.name );
System.gc();
}
}
the output is :
created : a
created : b
created : c
created : mother
created : child
a: a
b: b
c: b
d: child
a.aob: b
freed : mother
freed : c
You see it creates 5 A objects named a, b, c, mother and child.
Then you pull your little shell game.
When in is all done, objects a, b, and child are still pointed to.
mother and c are dangling, ready for GC to pick them off.
You may have have confused yourself by cascading the = operator:
A d=new A("mother").aob=new A("child");
leaves d pointing to child, not mother!!!
--
Roedy Green Canadian Mind Products
http://mindprod.com
If everyone lived the way people do in Vancouver, we would need three more entire planets to support us.
~ Guy Dauncey