这是我的代码。
public class FinalizableObject {
@Override
protected void finalize() throws Throwable {
System.out.println("finalize() invoked for " + this);
super.finalize();
}
}
public class Main {
private static void test() throws InterruptedException {
ReferenceQueue<FinalizableObject> rq = new ReferenceQueue<FinalizableObject>();
FinalizableObject obj = new FinalizableObject();
PhantomReference<FinalizableObject> pr1 = new PhantomReference<FinalizableObject>(obj, rq);
obj = null;
System.gc();
Reference<? extends Object> ref = rq.remove();
System.out.print("remove " + ref + " from reference queue\n");
}
public static void main(String[] args) {
try {
test();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
非常奇怪,rq.remove() 将永远被阻塞。为什么我的终结对象的虚引用不能放入引用队列中?它已经被GC收集了吗?
finalize()
方法,JVM构造了特殊的Finalizer线程,这个线程也必须被收集和完成。 - AndremoniyMain()
类中创建public static volatile boolean flag;
,在finalize()
方法中设置此标志,然后在Main()
中等待,直到此标志被设置(在第一个.gc()
后)。之后,您可以再调用一次System.gc()
。这就足够了。 - Andremoniy