Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can other methods be called after finalize()?

Tags:

java

finalize

If I have

public class Foo {
    private boolean finalized = false;

    public void foo() {
        if (finalized)
            throw new IllegalStateException("finalize() has been called.");
    }

    @Override public void finalize() {
        super.finalize();
        finalized = true;
    }
}

Is it guaranteed, even in the face of multiple threads, assuming only the GC will call finalize(), that the IllegalStateException will never be thrown?

I know that in the face of a finalize() method that causes the object to be not garbage-collectable, the object won't be garbage collected and other methods might be called. But this finalize() doesn't do that. Is there still a possibility of foo() being called after finalize()?

like image 794
Owen Avatar asked Mar 13 '23 00:03

Owen


1 Answers

It's entirely possible that a different object which had a reference to the instance of Foo is being finalized at the same time - and may resurrect the Foo object, allowing it to be used after finalization. This is kinda rude, but can certainly happen.

Even without resurrection, another finalizer could call Foo.foo() from its finalizer:

public class Bar {
    private final Foo foo;

    @Override protected void finalize() {
        // The finalizer in foo may already have executed...
        foo.foo();
    }
}
like image 124
Jon Skeet Avatar answered Mar 31 '23 08:03

Jon Skeet