当一个对象符合垃圾收集器的条件时? [英] when an object is eligible for a garbage collector?
问题描述
1。 public class GC {
2. private Object o;
3. private void doSomethingElse(Object obj){o = obj; }
4. public void doSomething(){
5. Object o = new Object();
6. doSomethingElse(o);
7. o = new Object();
8. doSomethingElse(null);
9. o = null;
10.}
11.}
当调用doSomething方法时,之后在
5行中创建的对象是否可用于垃圾回收?
A。第5行
B。第6行
C。第7行
D。第8行
E。第9行
F。第10行
答案:D
为什么D?确实,当执行第6行时,第5行中创建的对象现在由实例var o和本地var o引用,并且当执行第8行时,对象现在仅由本地ref var o引用,为什么答案是D,执行第9行后会发生什么?感谢。
这个问题让IMO感到困惑的主要原因是有两个变量名为 o
。一个是实例变量 o
,另一个是局部变量 o
方法 doSomething( )
。
时间实例var o本地变量o
在行5之前:null
行5:null对象#1
行6:对象#1对象#1
行7:对象#1对象#2
行8:空对象#2 <没有更多的引用对象#1
所以在(或执行后)第8行,对象#1有资格收藏。
consider this sample code:
1. public class GC {
2. private Object o;
3. private void doSomethingElse(Object obj) { o = obj; }
4. public void doSomething() {
5. Object o = new Object();
6. doSomethingElse(o);
7. o = new Object();
8. doSomethingElse(null);
9. o = null;
10. }
11. }
When the doSomething method is called, after which line does the Object created in line 5 become available for garbage collection?
A. Line 5
B. Line 6
C. Line 7
D. Line 8
E. Line 9
F. Line 10
Answer: D
why D? it's true that when Line 6 is executed the object created in Line 5 is now referenced by the instance var o and the local var o and when Line 8 is executed the object now is referenced by only the local ref var o, so why the answer is D and what happens after Line 9 is executed?? thanks.
The main reason this question is confusing IMO is that there are 2 variables named o
. One is the instance variable o
and the other is the local variable o
inside method doSomething()
.
Time instance var o local var o
Before Line 5: null
Line 5: null Object#1
Line 6: Object#1 Object#1
Line 7: Object#1 Object#2
Line 8: null Object#2 <- No more references to Object#1
So on (or after executing) line 8, Object#1 is eligible for collection.
这篇关于当一个对象符合垃圾收集器的条件时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!