Domanda

Directly from this API:

If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

I have tried to call finalize() explicitly after having overridden it as follows:

 public void finalize() // 
    {
        System.out.println("Garbage Collected");
        throw new RuntimeException();
    }

When I call it explicitly though I do get the exception, on the other hand if I let it go implicitly it goes fine ignoring the exception as expected:

public static void main (String []args) throws Exception
{
B b = new B();
b=null;// LINE 3

System.gc(); // It prints "Garbage Collected" and do not throw the exception
//if it was b.finalize() instead of System.gc() and line 3 was commented out it would print Garbage Collected and then would throw the exception.

Why does it happen? why in the first way using System.gc() the API are respected and when called explicitly are not?

È stato utile?

Soluzione

99.99% of the time, you don't want to call finalize() manually, as it will be implicitly called by the JVM when all references to the object are closed, and as such the best way to remove the object is to manually null all the references to it you have, and let the Garbage Collector work on its own.

When the call is made implicitly, there are no longer any references to the object and thus the exception has nothing to catch it, whereas in the explicit call, the reference to the object will exist until after the call has finished.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top