I know in Java we have concept of soft reference. What if:
1) There is a soft reference "sf" refer to an object A
2) In object A, it has a strong reference refers to object B
3) object A & B are not referenced anywhere else.
By definition, object A and object B are both "softly reachable", right?
Then say we are running out of memory now, GC kicks in. Is it possible that GC will recycle object B but not object A?
If that's the case, later if we want to access object B through "sf", it will be null. How java avoid such case to happen?
I don't see any explain in java doc.
No. The GC will not break strong references in reachable objects. (It will, of course break references in unreachable objects as part of the reclamation process. But you can't observe that happening ... because to observe it, you'd need the object to still be reachable.)
This is a consequence of this statement in the javadoc for the
java.lang.ref
package."Finally, an object is unreachable, and therefore eligible for reclamation, when it is not reachable in any of the above ways."
... where "the above ways" includes strong, soft, weak and phantom reachability.
The two highlighted words mean that eligibility for reclamation is a consequence of being in the unreachable state. Since none of the other states mention reclamation eligibility, we conclude that non-reachability is a precondition for reclamation.
This certainly aligns with common sense. If (hypothetically) the GC was allowed to "null out" strong references in reachable objects, it would be impossible for an application to safely work with objects after they had gotten into this state. (Consider the case where the nulled-out reference was in an instance of a library class ...)