I know what WeakReference
is and I read its documentation and many blogs and SO threads. However, it is still unclear to me whether the following flow can actually happen.
X
being referenced with strong reference strRef
and weak reference weakRef
strRef
is being cleared on a random threadweakRef
is being dereferenced on a random threadstrRef
There are many discussions about how weak references are being cleared upon GC, but, to the best of my knowledge, GC does not happen after each reference clearance. Therefore, it looks like a weakly reachable object could potentially be "resurrected" by the step #3 above if GC did not happen between steps #2-#3.
Such a race condition is very inconvenient and even dangerous, therefore I think that there should be something that prevents it, but I want to be completely sure here.
So, is there a specification that ensures that weakly referenced objects can't be resurrected, and are there any caveats related to multithreading?
Therefore, it looks like a weakly reachable object could potentially be "resurrected" by the step #3 above if GC did not happen between steps #2-#3.
Correct, even if a GC it has run, not all weak references have to be cleared e.g. when a minor collection is run an object in tenured space is not cleaned up. Only a Full GC can ensure all weak references are cleared.
Such a race condition is very inconvenient and even dangerous, therefore I think that there should be something that prevents it,
It's something you must check for at any point given you have no idea when the background thread clears the strong reference. NOTE: clearing a strong reference just means setting a memory value to null
nothing more.
is there a specification that ensures that weakly referenced objects can't be resurrected, and are there any caveats related to multithreading?
Even discarded object can be resurrected by setting a reference to this
in the finalise
method. I would recommend you not rely on this behaviour. References setting are not a source of messaging nor an operation which has much thread safety guarantees.
I thought I could rely on weak references in order to subscribe these UI classes to an event bus, such that there will be no need to unsubscribe them later.
You can but you have to check whether the listener is still active. Just because you could get a weak reference to it doesn't mean you didn't intend to discard it.