【发布时间】:2015-03-09 21:47:50
【问题描述】:
好吧,我尝试让一个最终确定的对象再次可用。我知道(来自oracle docs)finalize() 不会再次被调用。但是如果它变得无法访问会发生什么? 什么时候进行 GC?.
代码:
public class Solution {
static ThreadGroup stg = null;
static Solution ss = null;
protected void finalize() throws Throwable {
System.out.println("finalized");
System.out.println("this : " + this);
ss = this;
}
public static void main(String[] args) {
Solution s = new Solution();
s = null;
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ss);
ss = null; // My question. What happens now?. Solution@7f5f5897 has just become unreachable. Will it be GCed without "finalize()" being called on it? (looks like that..). If yes, then how can I find out when exactly has it become eligible for gc (Please don't tell me to look at source code "==null" check :P)
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
O/P:
finalized
this : Solution@7f5f5897 // printed in finalize()
Solution@7f5f5897 // printed in main()
【问题讨论】:
-
这叫复活。
-
@chrylis - 哦。有趣的是,Oracle 文档没有提到这一点。谢谢:)
-
我认为这不一定是官方术语,因为您绝对不应该这样做,但这是可能的,并且人们已经设法编写了使 JVM 翻转为一种运动。