A
ankur
Can objects be garbage collected without calling finalize ? How does
that work ?
In this code finalize was called once and exceptions were thrown and
so objects remained eligible and were not garbage collected. Next time
however the objects were garbage collected without calling finalize
( because finalize is only called once on an object).
package pack4;
class HeavyClass
{
long[] arr = new long[100000];
public void finalize() throws Throwable
{
System.out.println("In finalize");
throw new Throwable();
}
}
public class FinalizerCheck
{
public static void main(String[] args)
{
System.out.println(Runtime.getRuntime().freeMemory());
HeavyClass obj1 = new HeavyClass();
HeavyClass obj2 = new HeavyClass();
HeavyClass obj3 = new HeavyClass();
System.out.println(Runtime.getRuntime().freeMemory());
obj1 = null; obj2 = null; obj3 = null;
System.gc();
try
{
Thread.sleep(5000);
}
catch(Exception e)
{}
System.out.println(Runtime.getRuntime().freeMemory()); //3
System.gc();
System.out.println(Runtime.getRuntime().freeMemory());
}
}
Sample output :
4993000
2666136
In finalize
In finalize
In finalize
2638256 //3
5066280 //4
notice that 3 indicates the objects are not garbage collected first
time around but at 4 they are garbage collected without calling
finalize .
that work ?
In this code finalize was called once and exceptions were thrown and
so objects remained eligible and were not garbage collected. Next time
however the objects were garbage collected without calling finalize
( because finalize is only called once on an object).
package pack4;
class HeavyClass
{
long[] arr = new long[100000];
public void finalize() throws Throwable
{
System.out.println("In finalize");
throw new Throwable();
}
}
public class FinalizerCheck
{
public static void main(String[] args)
{
System.out.println(Runtime.getRuntime().freeMemory());
HeavyClass obj1 = new HeavyClass();
HeavyClass obj2 = new HeavyClass();
HeavyClass obj3 = new HeavyClass();
System.out.println(Runtime.getRuntime().freeMemory());
obj1 = null; obj2 = null; obj3 = null;
System.gc();
try
{
Thread.sleep(5000);
}
catch(Exception e)
{}
System.out.println(Runtime.getRuntime().freeMemory()); //3
System.gc();
System.out.println(Runtime.getRuntime().freeMemory());
}
}
Sample output :
4993000
2666136
In finalize
In finalize
In finalize
2638256 //3
5066280 //4
notice that 3 indicates the objects are not garbage collected first
time around but at 4 they are garbage collected without calling
finalize .