JavaMemoryModel: Finalization idioms

From: Boehm, Hans (
Date: Sat Apr 30 2005 - 14:40:01 EDT

I'm giving a talk at JavaOne about finalization and the memory model.

The final version of the memory model requires some explicit precaution
to prevent the finalizers from running before ordinary methods
complete their actions (except that constructors have special
and happen before the finalizer).

We failed to include any explicit recommendation or library routine
to enforce the necessary ordering, though we discussed it extensively.

There are several possible idioms that might be used to enforce that
the correct thing happens:

1) Make all methods which might be the last ordinary call on an
object synchronized. Make the finalizer synchronized.

2) Write to a volatile field at the end of ordinary methods,
and read it first thing in the finalizer.

3) Put "synchronized(this){}" at the end of ordinary methods and at
the beginning of finalizers.

I originally was thinking in terms of (1) as the standard mechanism.

But the more I think about it, there is no clear winner. Option (2)
is almost certainly ugliest and fastest. Stylistically, option (3)
looks cleanest to me, and allows more optimization than (1). If you
want to be 100% correct, (2) and (3) may require a try ... finally to
ensure that the synchronization operation can be executed on exceptional
paths. (It seems REALLY unlikely that a compiler would
optimize away the "this" pointer because it knows that a method is
always going to generate an exception.)

I think I'm inclined to go with (3) in my main example.



JavaMemoryModel mailing list -

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