How's the following?
If you like this one, I can also generate a much messier
clarification/enhancement request for System.runFinalization.
In my view, this is currently so underspecified as to be
(I wouldn't trust my taste in adding this to java.lang.ref.Reference
instead of somewhere else. You shouldn't either. It really
belongs in java.lang.Object, but ...)
public void keepAlive(T x)
The keepAlive method is intended to ensure that an object
is considered reachable by the garbage collector, for purposes
of both finalization and References up until that point.
A call to keepAlive(x) is equivalent to assigning to a hidden
volatile field inside x. This volatile field is implicitly
read just before a finalizer is executed or a reference is
enqueued by the garbage collector.
This is much cheaper to implement inside the VM than any
method for accomplishing the same thing in Java code.
The only known technique for solving this problem with Java
code in the context of References is to store a pointer
to the object into a static volatile field, and then
immediately clear it, and to read that static field when
the Reference is dequeued. This is expensive and
introduces contention, which inhibits processor scalability,
for no sane reason.
Typical implementation outline:
Forces x to remain GC reachable, by keeping it in a register
or on the stack, until after the last load or store instruction
corresponding to earlier code. (For a safe-point-based
implementation, it only needs to be kept GC-reachable through
the last safe point that precedes any such memory instruction.)
Typically no actual code or memory barriers have to be generated,
since the GC will pause the affected thread. By doing so, it
will wait for all pending instructions to complete. And in
all implementations of which I'm aware, the GC happens-before
finalizer invocations and enqueuing of References.
> -----Original Message-----
> From: Doug Lea [mailto:email@example.com]
> Sent: Tuesday, May 03, 2005 12:00 PM
> To: Boehm, Hans
> Cc: javaMemoryModel@cs.umd.edu
> Subject: Re: JavaMemoryModel: Finalization idioms
> > I think we really need keepAlive in the library. Perhaps
> > java.lang.ref is a good place to put it. If you implement in the
> > standard library, with suitable VM cooperation, it should be nearly
> > free. .NET has GC.KeepAlive which I believe can be used for this
> > purpose, though the primary motivation there seems to be different.
> If anyone would like to put together a proposal for this,
> along with a sample implementation sketch (or even better,
> sign up as a Mustang contributor at http://java.net and help
> implement) there's an audience for this sort of thing in the
> "miscellaneous but important RFE" subgroup of the Mustang
> JSR, that I'm on, so I could help push along.
JavaMemoryModel mailing list - http://www.cs.umd.edu/~pugh/java/memoryModel
This archive was generated by hypermail 2b29 : Thu Oct 13 2005 - 07:01:10 EDT