[concurrency-interest] Thread safety of WeakReference .get() method?

Aleksey Shipilev aleksey.shipilev at oracle.com
Tue Aug 7 09:49:01 EDT 2012

On 08/07/2012 04:47 PM, Raph Frank wrote:

> The documentation says that once an object has been determined to be
> garbage collectable, "At that time it will atomically clear all weak
> references to that object", so presumably, the get method can be
> called, some if is atomically set to null?

I think the real meaning behind that claim is "atomically set *all* weak
references to that object", i.e. two weak references to the same object
will simultaneously become clear once object is not reachable.

Mutator threads are not modifying the referent, and so the real question
should be: is it possible to read the non-null referent after weak
reference is cleared? There is no difference how many user threads are
accessing now, because the possible race is between mutator threads and GC.

The answer to that is VM-specific. Common sense is that all GC
operations should be committed before returning back to the mutator
after stop-the-world, or notified to the mutator as soon as possible in
concurrent GCs. If that wasn't true, WeakRefs would risk keep
referencing the objects that are not really there, and it would broke
too many applications already.


More information about the Concurrency-interest mailing list