Is it possible to call other methods after 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 this guaranteed even in the face of multiple threads, if only the GC calls finalize()that it IllegalStateExceptionwill never be selected?

I know that in the face of a method finalize()that causes an object not to collect garbage, the object will not be garbage collected, and other methods can be called. But that finalize()does not do it. Is there still an opportunity foo()to be called after finalize()?

+4
source share
2 answers

, , Foo, - Foo, . , , , .

Foo.foo() :

public class Bar {
    private final Foo foo;

    @Override protected void finalize() {
        // The finalizer in foo may already have executed...
        foo.foo();
    }
}
+7

, , , .

, .

public class Foo {
    private boolean finalized = false;

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

    @Override public void finalize() {

        synchronized (this)
        {
            super.finalize();
            finalized = true;
        }
    }
}

. , super.finalize() try/finally:

@Override public void finalize() {

        synchronized (this)
        {
            try
            {
                super.finalize();
            }
            finally
            {
                finalized = true;
            }
        }
    }
0

All Articles