gpt4 book ai didi

java - 如果我再次使 "finalized"对象可用,它会发生什么情况?

转载 作者:行者123 更新时间:2023-11-30 07:04:03 25 4
gpt4 key购买 nike

好吧,我试着让一个完成的对象再次可用。我知道(来自 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();
}
}

订单:

finalized
this : Solution@7f5f5897 // printed in finalize()
Solution@7f5f5897 // printed in main()

最佳答案

是的,一旦它第二次变得不可访问,它将被 GC 处理,除了 finalize 不会再次调用它。

您可以使用 WeakReference 确认这一点。

static WeakReference<Solution> ref;

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);
ref = new WeakReference<Jackson>(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.out.println(ref.get()); // (hopefully) prints object
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ref.get()); // prints null
}

因此 WeakReferenc 被清除,表明该对象已被 GC 处理。 (从技术上讲,当对象变得弱可达时,WeakReference 会被清除。但在这种情况下,由于您随后无法使其可达,它将被 GC 处理。)

关于java - 如果我再次使 "finalized"对象可用,它会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27896718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com