Fwd: [concurrency-interest] Atomicity of clearing of WeakReferences
martinrb at google.com
Sat Jul 18 07:31:36 PDT 2009
I'm forwarding this message from concurrency-interest.
Lots of stuff on that mailing list for those interested in
reclamation of weak references.
---------- Forwarded message ----------
From: Gregg Wonderly <gregg at cytetech.com>
Subject: Re: [concurrency-interest] Atomicity of clearing of WeakReferences
To: Karnok Dávid <karnok at sztaki.hu>
Cc: concurrency-interest at cs.oswego.edu
If you need to cleanup after something is unreferenced,
PhantomReference may be a good choice. I used it to construct my
ReferenceTracker class ( see
The one warning I will give, is that after doing this, I found that I
just could not use it in all the places I wanted, because of the Sun
JVM "bug" that nominates objects for finalization, before ALL
references are out of scope.
This causes the objects to be posted to the ReferenceQueue before they
are actually "dead". This means that any state you change, which is
referenced by that object, in finalization, can be seen by the object
before all references to the object have been used and gone out of
scope. Hans went into a lot of detail about this issue in many
contexts it seems (see
follow up to the long trail of posts comming from Doug Lea's post at
which is the fences API discussion. Without Fences, or some other
mechanics in the JIT to automatically manage this issue, it's not much
of a real solution because you have to always think about scoping to
make sure that refences last longer than the JIT currently documents
them to exist as visible by the GC. And PhantomReference would really
help developers to not have to worry so much about scoping...
This is a tricky issue I discovered and I'd say that the way it works
now is wrong, if not an out right bug. Finalization should not be
invoked (directly or indirectly through PhantomReference queues etc)
until there are no more references to the value in registers, on the
stack, or in scoped variables etc.
This misbehavior really makes automated reference tracking for limited
resources nearly impossible when they are used by short lived bits of
code that are prime for optimization and registerization that appears
to hide references from the GC.
More information about the hotspot-gc-dev