I'm reading about WeakReference
in wikipedia and I saw this code
public class ReferenceTest {
public static void main(String[] args) throws InterruptedException {
WeakReference r = new WeakReference(new String("I'm here"));
WeakReference sr = new WeakReference("I'm here");
System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
System.gc();
Thread.sleep(100);
// only r.get() becomes null
System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());
}
}
When It runs this is the result
before gc: r=I'm here, static=I'm here
after gc: r=null, static=I'm here
sr
and r
variable are both referring string objects. r
is now garbage collected but, why sr
didn't garbage collected after calling garbage collector?
I'm just curious how this happened.