Search code examples
javagarbage-collectionweak-referencesstrong-references

when strong reference directly access weak reference


In Java, when an target object A is only reached by weak reference B, A can be GC. what happen if the weak reference B is reached by a strong reference C at same time? For exmaple, C points to a class instance which contains a field of weak reference B which points to A. If C is live, and there is no other weak or strong reference to obj A, can A still be GC?


Solution

  • Yes, since there is one weak refence as a link it is considered weakly reachable. The Wikipedia entry on Weak reference says (in part)

    A weak reference is a reference that does not protect the referenced object from collection by a garbage collector, unlike a strong reference. An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time.