The Artima Developer Community
Sponsored Link

Legacy Design Forum
Finalization and Cleanup

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

WeakReference Specification

Posted by Aaron Lehmann on March 21, 2000 at 11:41 AM

I am writing a GUI for Sun's command-line javac, mainly for educational purposes, but also hoping to get use out of it. I've reached the part where I deal with opening and saving files. In order to ensure that no file is ever being written to and read at the same time, I'm creating a class that will sit in memory and keep track of all the files I'm using. That way I'll be able to synchronize on the File objects. My problem is that if I use regular references in the manager class, File will not be garbage collected, nor will file handles be released. I was hoping to make a Vector of WeakReferences to the objects, since that would (theoretically) cause the GC to kill the File off for me when I was no longer using it. Unfortunately, a test program a I wrote seems o be telling me that I'm not using WeakReferences correctly:

import java.lang.ref.*;

public class test
{
public static void main(String[] args)
{
String a = new String("This object is uncollected!");
WeakReference b = new WeakReference(a);
System.out.println(b.get());
//Remove strong reference to the String
a = null;
//Call garbage collector...
System.gc();
//Shouldn't the String be finalized?
if(b.get() == null)
System.out.println("It works!");
else // This is the condition that is executed
System.out.println(b.get());
System.exit(0);
}
}

This program was compiled and run under Sun's JDK 1.2.2 compiler, and the output was:

This object is uncollected!
This object is uncollected!

Why didn't the second line say, "It works!"? Any help or explanation on WeakReferences or the GC would be appreciated.
Aaron Lehmann



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us