问题
This question is about understanding the Java documentation for WeakReference
When I read about Java's WeakReference, I came across this sentence in the documentation:
Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references
But this doesn't make sense to me. Suppose I have a WeakReference wrA referencing an object A and another WeakReference wrB referencing an object B. And B strongly refers to A (directly or indirectly through a chain). Now according to the document, if A becomes weakly reachable and if B is already weakly reachable at that time, then wrB will be cleared together with wrA. However, since B is already weakly reachable at that time, shouldn't wrB already be cleared at an early time when the weak reachability of B is first detected?
回答1:
since B is already weakly reachable at that time, shouldn't wrB already be cleared at an early time when the weak reachability of B is first detected?
This happens at the same time, so there is no earlier time. When a GC starts all objects (e.g. both A and B) which are not strongly reachable at that time are eligible to be cleaned up at that time.
来源:https://stackoverflow.com/questions/27463048/contradiction-in-weakreferences-java-documentation