Reputation: 3
public class SuperClass {
private final Object finalizerGuardian = new Object(){
@Override
protected void finalize(){
System.out.println("SuperClass finalize by the finalizerGuardian");
}
};
@Override
protected void finalize(){
System.out.println("SuperClass finalize by the finalize method");
}
public static void main(String[] args) throws Exception{
SubClass sub = new SubClass();
sub = null;
System.gc();
Thread.sleep(500);
}
public class SubClass extends SuperClass{
@Override
public void finalize(){
System.out.println("SubClass finalize by the finalize method");
}
Its a finalizerGuardian in the anoymous class,why this finalizerGuardian always be called when the superclass was running?thx.
Upvotes: 0
Views: 60
Reputation: 2066
Even if the finalizerGuardian is an anonymous class it is known to the GC. So when the GC runs it looks for objects that can be cleaned from memory and calls their finalize()-method.
Each time you have an instance of your SuperClass an instance of your finalizerGuardian will be constructed and therefore is available for the GC.
Upvotes: 0
Reputation: 552
finalizerGuardian is an instance (not static or class variable) object, and since you have removed/null'ed the reference to SubClass, the unreferenced instance object finalizerGuardian is also collected immediately.
Being an instance object, it is live only till the SubClass is alive.
Upvotes: 0
Reputation: 237
It is because there is no reachable SuperClass
instance when System.gc()
is called. Finalize guardian object is instance property and so it has to be finalized. There is no such entity as "class, that is running".
The main
method is indeed in super class, but it means nothing about its instances.
Upvotes: 1