【发布时间】:2020-01-19 16:39:45
【问题描述】:
我担心的是一个曾经被强引用的对象的实例,但是在对其强引用显式分配空值和显式调用System.gc() 之后,该实例仍然可以通过弱引用。如果我理解正确,当被引用对象只剩下弱引用时,保证在下一个 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);
}
}
【问题讨论】:
-
垃圾收集不是一个可预测的过程。它可能只是在第一次扫描中标记对象,然后在下一次清除。所以任何依赖 GC 进程的行为都是不确定的。
-
我会把它作为这个问题的答案。谢谢!
-
更不用说,不能保证
System.gc()会做任何事情。
标签: java reference weak-references