我关心的是曾经被强引用的对象的实例,但是在对其强引用进行显式的空赋值以及显式的System.gc()
调用之后,该实例仍然可以通过 weak到达参考。如果我理解正确,当所引用的对象仅剩下弱引用时,可以确保在下一个 GC 会话中清除该引用。我想念什么?
参考代码:
public class References {
public static void main(String[] args) {
Example strongReferenceWrappedInWeak = new Example(42);
strongReferenceWrappedInWeak.printA();
WeakReference<Example> exampleWeakReference = new WeakReference<>(strongReferenceWrappedInWeak);
System.gc();
Example retrievedExample = exampleWeakReference.get();
retrievedExample.printA(); //this works,because a strong reference is present to the instance,hence it's not cleared
strongReferenceWrappedInWeak = null; //eligible for garbage collection
System.gc();
Example retrievedExampleTwo = exampleWeakReference.get(); //should be null
retrievedExampleTwo.printA(); //should throw NPE
}
}
class Example {
private int a;
Example(int a) {
this.a = a;
}
void printA() {
System.out.println(this.a);
}
}