Xueming Shen said the following on 04/02/11 17:00:
 On 4/1/2011 4:17 PM, David Holmes wrote:
Xueming Shen said the following on 04/02/11 05:07:
...
explicit invocation is cleared. The InputStream is eligible for finalization only after it is
"weakly" reachable, means no more "stronger" reachable exists, right?

Actually no. One of the more obscure corner cases with finalization is that you can actually finalize an object that is still being used. The JLS actually spells this out - see section 12.6.1 and in particular the Discussion within that section.

The scenario that Neil and I were discussing is something like this,

There is class A

class A {
    void close() {
        ...
    }

    protect void finalize() {
        ...
        close();
    }

}

when we are in the middle of A's close() (invoked by someone, not the finalizer), do we need to worry about that A's finalize() being invoked (and then the close()) by the finalizer concurrently.

Does you "an object that still being used" include the scenario like above, which means an object became finalizer-reachable, when still in the middle of the execution (by some alive, non-finalizer-thread) of one of its
instance method body?

The JLS 12.6.1, if I read it correctly, is for scenario that a reachable object which is strongly referenced by a stack reference can/may become finalizer-reachable sooner than it might be expected, for example, the compiler optimization can null out such reference in the middle of the method body, so that object becomes finalizer-reachable before the execution reach the return point of the method, or ... The "execution" discussed is not the execution inside the target object's method body. Am I reading it correctly? Otherwise, it becomes a little weird, image, you are in the middle of the execution of an instance method, suddenly, the instance itself
is being finalized, all the native resource get released...

Yes 12.6.1 refers to the case where the object is only strongly-reachable from a local stack reference. This includes the "little weird" scenario you describe. A thread can be executing a.close() where 'a' is a local stack reference, and 'a' can be finalized while that is heppening.

I'm not saying hotspot will actually do this, but it is permissible within the spec. This situation has been discussed quite a bit in the past on the Java Memory Model mailing list.

David

-Sherman




Reply via email to