Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

java - Finalization of object fields

I'm having difficulty understanding the implications of sections 12.6.1 and 12.6.2 of the Java SE 8 Language specification. I am working with a product in which Java objects manage native peers so getting finalization right (until we get a chance to do a ref-queue rewrite) is important.

It is clear, from the spec, that finalizers can be run out of order. It is reachability with which I'm having a hard time.

I believe that the spec says this:

class A {
    public Object o = new Object()
    protected synchronized void finalize() throws Throwable { o = null; }
}

class B {
    A a = new A()
    protected void finalize() throws Throwable {
        a.getClass()   // always works: a cannot be null.
        a.o.getClass() // might NPE: a's finalizer might have been run
    }
}

class C {
    A a = new A()
    protected void finalize() throws Throwable {
        synchronized (a) {
            a.getClass()   // always works: a cannot be null.
            a.o.getClass() // always works: a.o cannot be null.
        }
    }
}

There are 4 assertions, above. I would very much appreciate confirmation that they are true, or explanations for why one or more is false.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If A.finalize acquires the lock first, then a.o.getClass() will NPE even in C. The final assertion is incorrect.

In terms of reachability think of it like this: Suppose A and C were cyclically reachable, then the would reach unreachability at the "same time". So, it cannot reasonably be that A must be finalised before C.

I guess a direct fix could be reference counting of A. However, relying on GC to clear up non-memory resources isn't going to be great.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...