gpt4 book ai didi

java - 对象何时有资格进行垃圾回收

转载 作者:行者123 更新时间:2023-12-01 07:35:04 28 4
gpt4 key购买 nike

给我一​​个方法,询问它何时有资格进行垃圾收集,我的意思是在哪一行。我相信 ooa 都有资格进行垃圾回收。因为,它们被设置为null。如果我错了,请纠正我。但是,问题是,什么时候它有资格进行 gc,我的意思是在哪一行。 ?

public Object m() {
Object o = new Float(3.14F);
Object[] oa = new Object[1];
oa[0] = o; /* Line 5 */
o = null; /* Line 6 */
oa[0] = null; /* Line 7 */
return o; /* Line 8 */
}

请大家解释一下。 ?

最佳答案

让我们看一下代码:

1)  o = new Float();  
2) oa = new Object[];
at this point we have 2 objects.
3) oa[0] = o;
at this point oa[0] holds the reference of o.
4) o = null;
o is still being referenced by oa[0]
5) oa[0] = null
o now has zero references.
6) return o;
o is null.

第 7 行是 o 发生 GC 资格的地方。在函数退出之前,oa 不符合 GC 的条件。

一般来说,一个对象只有在没有任何引用时才符合 GC 的条件。处理String 时要非常小心,因为有一个特殊的地方称为字符串池。所以下面的代码:

void foo()  
{
String s = "foo";
s=null;
return s;
}

在任何时候都不能保证 s 符合该函数的条件。

评论中的问题

one question, you said..oa is not eligible for GC until the function exits. but, before the return o, oa set to be null and it nowhere referred too

答案:

oa is not set to null. What gets set to null is the object at oa[0] (the first index of oa). If the line was oa = null that would be true, and irrespective of the only item in oa being null, does not in fact make the wrapper (in this case an array) null. Similar to having a List and nulling out all of its elements does not make the List null.

关于java - 对象何时有资格进行垃圾回收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13166316/

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