finalize() method breaks mid-execution?

176 Views Asked by At

Question

I have a URLClassLoader anonymous class. In it, I've overridden the finalize() method so that the object will automatically close itself when garbage collected:

protected void finalize() throws Throwable {
    close();
}

and I've overridden the close() method to print some information:

public void close() throws IOException {
    System.out.println("Closing...");
    super.close();
    System.out.println("Closed.");
}

Immediately after creating this object, I call System.gc() to destroy it. As expected, the finalize() method gets called, and then the close() method gets called, but I only see Closing... get printed to the console.

Why does execution never reach my second print statement?


Notes

The first thing that I suspected was happening was that super.close() was throwing an exception, and whatever prepares an object for garbage collection was swallowing the exception, so I tried catching any Throwable and printing it:

public void close() throws IOException {
    System.out.println("Closing...");
    try {
        super.close();
        System.out.println("Closed.");
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

But I got the same exact output as before: Closing.... The next thing I did was test what would happen if I closed the class loader manually, so I just called .close() on my class loader, immediately after constructing it, instead of running System.gc(); In this case, both of my print statements were run:

Closing...
Closed.
0

There are 0 best solutions below