[英]Java Garbage collection eligibility
I am preparing for OCJP exam. 我正在为OCJP考试做准备。 I am giving a mock test.
我正在进行模拟测试。 Here is a code snippet.
这是一个代码片段。
public class GC {
private Object o;
private void doSomethingElse(Object obj) {
o = obj;
}
public void doSomething() {
Object obj = new Object(); // Line 5
doSomethingElse(obj); // Line 6
obj = new Object(); // Line 7
doSomethingElse(null); // Line 8
obj = null; // Line 9
}
}
When the doSomething method is called, after which line does the Object obj become available for garbage collection? 调用doSomething方法时,对象obj在哪一行变为可用于垃圾回收?
I know the answer is Line 9 , however according to the exam simulator it is line 8 ? 我知道答案是第9行,但是根据考试模拟器,答案是第8行? I am not sure who is right ?
我不确定谁是对的?
The simulator is right. 模拟器是正确的。 In line 7, you overwrite the local hard reference to the instance, so the code in line 9 makes the second
Object
eligible for GC. 在第7行中,您覆盖了对该实例的本地硬引用,因此第9行中的代码使第二个
Object
可以使用GC。 The first one becomes eligible with line 8. 第一个符合第8行的条件。
Longer explanation: 更长的解释:
Line 5: create inst1
and assign to obj
第5行:创建
inst1
并分配给obj
Line 6: put inst1
into this.o
. 第6行:将
inst1
放入this.o
There are now two hard references to inst1
现在有两个硬引用
inst1
Line 7: create inst2
and assign to obj
. 第7行:创建
inst2
并分配给obj
。 this.o
still points to inst1
this.o
仍然指向inst1
Line 8: Clear reference this.o
, make inst1
available for GC 第8行:清除引用
this.o
,使inst1
可用于GC
Line 9: Clear reference obj
, make inst2
available for GC 第9行:清除引用
obj
,使inst2
可用于GC
在第5行中创建的对象可以在第8行之后进行垃圾收集,而在7中创建的对象在第9行中可以进行垃圾收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.