Suppose I have a weak reference to a car which has an ordinary reference to an engine. No other references to the car or the engine exist. Can the engine be garbage collected?
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:
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.
Here's a unit test that demonstrates weak references. Note that System.gc() will not guarantee that the object will get garbage collected and you should not rely on it.
import junit.framework.TestCase;
import java.lang.ref.WeakReference;
public class WeakReferenceTest extends TestCase {
class Car {
Engine engine = new Engine();
}
class Engine {
}
public void testWeakReferences() {
WeakReference<Car> carRef = new WeakReference<Car>(new Car());
assertNotNull(carRef.get());
System.gc();
assertNull(carRef.get());
}
}
The Car instance could be garbage collected, but there is no guarantee that it will be garbage collected on the next GC cycle, or even that it will be collected at all. For example,
At some time before the GC runs, the application could call
get
on theWeakReference
and save the reference to theCar
in (for example) an attribute of some reachable object. TheCar
instance then becomes fully reachable and no longer eligible for garbage collection.If the GC runs with the
Car
in the state described, the JVM spec does not guaranteed that the weakly reachable will be detected in the next GC cycle. For example, if a given GC cycle only collects the latest generation (and theCar
has been promoted to an older generation) the GC won't determine that it is weakly reachable.Even when the GC breaks reference to the
Car
in the WeakReference, theCar
instance is not reclaimed immediately. Rather, the reclamation of the now unreachableCar
will probably happen (after possible finalization) in a later GC cycle.