Re: Forcing garbage collection
Dan wrote:
In my test cases, the following seems to run it every time... but I
was hoping that there was a more definitive way to do it:
System.gc();
Thread.sleep(1000);
I don't think there's a way to force the gc to run, but in my experience
it always does run. You can, however, do something more deterministic
by using a phantom reference. Unfortunately, the Thread.sleep() call
seems to be necessary, so I don't know how deterministic this really is.
public class PhantomTest {
public static void main( String[] args )
throws Exception
{
ReferenceQueue<?> refQueue = new ReferenceQueue<Object>();
DiesHorribly die = new DiesHorribly();
PhantomReference<?> ref = new PhantomReference( die, refQueue );
System.out.println( "About to kill " + die );
die = null;
System.gc();
System.out.println( "Done." );
Thread.sleep( 1000 );
System.gc();
System.out.println( "waiting..." );
refQueue.remove();
System.out.println( "The phantom of the OS" );
}
private static class DiesHorribly {
@Override
protected void finalize()
throws Throwable
{
System.out.println( this+" died." );
super.finalize();
}
}
}