broken and correct

While looking for references on the web I cam across these two methids

publicstaticvoid broken()throws FileNotFoundException

{

System.out.println("Executing method broken");

FileReader obj = recreateIt();

WeakReference wr =new WeakReference(obj);

System.out.println("wr refers to object " + wr.get());

System.out.println("Now, clear the reference and run GC");

//Clear the strong reference, then run GC to collect obj.

obj =null;

System.gc();

System.out.println("wr refers to object " + wr.get());

//Now see if obj was collected and recreate it if it was.

obj = (FileReader)wr.get();

if (obj ==null)

{

System.out.println("Now, recreate the object and wrap it

in a WeakReference");

wr =new WeakReference(recreateIt());

System.gc();//FileReader object is NOT pinned...there is no

//strong reference to it. Therefore, the next

//line can return null.

obj = (FileReader)wr.get();

}

System.out.println("wr refers to object " + wr.get());

}

publicstaticvoid correct()throws FileNotFoundException

{

System.out.println("");

System.out.println("Executing method correct");

FileReader obj = recreateIt();

WeakReference wr =new WeakReference(obj);

System.out.println("wr refers to object " + wr.get());

System.out.println("Now, clear the reference and run GC");

//Clear the strong reference, then run GC to collect obj

obj =null;

System.gc();

System.out.println("wr refers to object " + wr.get());

//Now see if obj was collected and recreate it if it was.

obj = (FileReader)wr.get();

if (obj ==null)

{

System.out.println("Now, recreate the object and wrap it

in a WeakReference");

obj = recreateIt();

System.gc();//FileReader is pinned, this will not affect

//anything.

wr =new WeakReference(obj);

}

System.out.println("wr refers to object " + wr.get());

}

I have not been able to figure out why one is broken while the other is correct, they both seem identical to me

[3652 byte] By [kilyasa] at [2007-10-3 5:25:55]
# 1
Read the comments about the FileReader being "not pinned" versus "pinned" in that code.The broken one has no strong reference to the object, so just like the comment indicates, it may be garbage collected before the next line which attempts to obtain a reference to it.
warnerjaa at 2007-7-14 23:33:09 > top of Java-index,Java Essentials,Java Programming...
# 2
o thanx, now that I see it, it seems so obvious. Need some coffee I guess
kilyasa at 2007-7-14 23:33:09 > top of Java-index,Java Essentials,Java Programming...