RE: JavaMemoryModel: Finalization idioms

From: Hans Boehm (
Date: Sun May 01 2005 - 02:15:31 EDT

On Sun, 1 May 2005, David Holmes wrote:

> Hans,
> I'm a little confused - but given the context that is hardly surprising. You
> seem to be implying that the cure for this problem lies in the code of the
> class of the object we don't want prematurely finalized. My understanding of
> the problem was that it is only possible if the object is currently only
> referenced through a stack variable, rather than a heap variable. Hence it
> is the method of the class that *uses* the object that must take special
> steps to prevent premature finalization. So if the finalize() method is
> synchronized, or employ's synchronization, then the method using the object
> should have a "synchronized(theObj) {}" block to prevent the finalization
> from occurring prematurely.
I believe it works either way. You can also use a
synchronized(this){} at the end
of every ordinary method call which might be the last call on the
object. And it hides this mess inside the object with
the finalizer.

You are right that if the object is referenced through the heap
from a static field, none of this is necessary. But I still don't
think you want to expose this stuff to the client.
> The idea that any class with a finalizer should add a sync block to the end
> of all methods is just too horrible to contemplate. I'd probably prefer a
> write to a private volatile as a cleaner mechanism if this is the way to do
> this.
It's not good. If we had gotten keepAlive in, that would have been
better. Correcting my reply to Jeremy, I think the volatile field
would need to be in the object for this to work, adding space.
and you need the volatile assignment everyplace you would need the
synchronized block. So in terms of pure aesthetics, I think
I prefer the synchronized block, possibly in a keepAlive method,
In terms of performance, I agree with you.

I think synchronized(this){} can be implemented
on something like X86 with basically a single CAS instruction, to
test that the lock isn't held in a way that includes a full memory
barrier. That's probably still more expensive than the volatile
solution, unless the extra field has a substantial cache effect.
Clearly a standard keepAlive could be cheaper.
> BTW this is one talk I'll definitely be attending. :)
> Cheers,
> David Holmes
> -------------------------------
> JavaMemoryModel mailing list -
JavaMemoryModel mailing list -

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