JavaMemoryModel: Finalization, again

From: Boehm, Hans (hans_boehm@hp.com)
Date: Mon Dec 31 2001 - 16:50:29 EST


I'm still reading Jeremey's and Bill's paper.

In my opinion, it understates the case for synchronizing finalizers. (This
is only marginally relevant, but I think it's important.)

There is a potential race between multiple finalizers. But I don't think
that's the most important one. There are also very commonly races between
finalizers and user threads:

Consider an otherwise single-threaded application:

class B {
    void f() {
        // Caller must ensure that there is only one caller to x.f() at a
time.
        // For multithreaded clients, the client should synchronize.
        ...
    }
}

class A {
    private B x; // x has a unique reference from this object.
                        // It's logically a part of this object.
                        // x is initialized by the constructor(s).
    ...
    void g() {
        ...
        x.f();
    }
    protected void finalize() {
        ...
        x.f();
        ...
    }
}

The problem here is that

(new A(...)).g()

is thread-unsafe. There is no guarantee that the A object is still live
during the x.f() invocation from g(). Thus the finalizer may be run
concurrently with the explicit call.

This sort of thing is likely to happen whenever a finalizable object
contains some other subobject, which I suspect covers a large fraction (the
majority?) of finalizer uses.

It seems to be common to assume that an object is live as long as one of its
methods is executing. I don't believe that's guaranteed to be true. It
also isn't necessarily true for many implementations. (I suspect that in
this case synchronizing just g() would fix the problem for most
implementations, in that a reference to the object is usually needed to
release the lock. But even that isn't universally true, and I think is not
guaranteed by the memory model proposal.) The correct solution is usually
to synchronize both g() and finalize(), even if the user program is
single-threaded.

Hans

-------------------------------
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel



This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:00:36 EDT