Re: JavaMemoryModel: Finalization idioms

From: Jeremy Manson (
Date: Sun May 01 2005 - 02:36:14 EDT

Hans Boehm wrote:
> Thanks. More details follow.
> How do you implement keepAlive in Java code? You really want to
> ensure visibility of writes (to outside the object) from ordinary
> methods to finalizer code. I think that means that without the
> implicit volatile read in the finalizer, you need an explicit
> read or other synchronization action in the finalizer, too.

You do need something at the finalizer. IIRC, the code looks like this:

public class FinalizerHelp {
     static volatile Object v;
     public static void keepAlive(Object o) {
       v = o;
       v = null;
     public static void doFinalize() {
       Object o = v;

and it works because it stores a reference to the object into the heap.
    Although doFinalize is nasty, it is cleaner looking than lots of
volatile stuff / empty sync blocks, at any rate.

> You usually end up with an otherwise unnecessary volatile field,
> which either costs you space or potential contention (if you make
> its static). And you end up with assignments everywhere you would
> have the empty sync blocks.

On the other hand, an assignment is probably cheaper than a lock
acquisition, and it is nice to have the volatile field as documentation
of "hey, we want to be able to finalize this object".

>>4) We still should have some sort of built in keepAlive method. And a
>>way of initializing final fields sensibly. This is neither here nor
>>there, really :)
> Agreed. But we're in much better shape than before JSR133.
> And for now we need some (stop-gap?) programming guidelines.

Definitely. Number 1: "Avoid finalizers" ;)

JavaMemoryModel mailing list -

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