Here I have an example:
import java.lang.ref.WeakReference;
public class WeakRefTest {
public static void main(String[] args) {
Object obj = new Object();
WeakReference<Object> weakRef = new WeakReference<Object>(obj);
int i = 0;
while (true) {
if (weakRef.get() != null) {
i++;
System.out.println("The object is alive for " + i + " loops - " + weakRef);
} else {
System.out.println("The object has been collected.");
break;
}
}
}
}
When running this program, we'll get output with "The object has been collected."
after a while, which means the object will be gc-ed.
However, there is still a strong reference named "obj"
linked to the object, how can it be reclaimed? Because JVM found there is no strong reference usage later, so it's not strong reachable?