Carlos
Carlos

Reputation: 3

About the finalizerGuardian

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

Answers (3)

Frank
Frank

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

Vijay
Vijay

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

Marat
Marat

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

Related Questions