weak reference to object containing a nested strong reference, and garbage collection

fredoverflow picture fredoverflow · Apr 6, 2010 · Viewed 7.7k times · Source

Suppose I have a weak reference to a car which has an ordinary (strong) reference to an engine. No other references to the car or the engine exist. Can the engine be garbage collected?

Answer

Andrew Hare picture Andrew Hare · Apr 6, 2010

Yes it can, that is exactly how weak references are designed to work. The weak reference is the root that your object has to the application, even though the object may have other strong references it is the root reference that matters and since the root reference is a weak reference the object will be a candidate for garbage collection.

For more information please see WeakReference class documentation:

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.

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. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.

FYI, along with WeakReference, Java offers two other subclasses of Reference: SoftReference and PhantomReference.