when an object is eligible for a garbage collector?

耗尽温柔 提交于 2019-12-06 06:27:22

问题


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.


回答1:


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.




回答2:


The question is a bit confusing because it is after line 3 is called the second time that the object is eligible because it clears the second reference o.



来源:https://stackoverflow.com/questions/12182383/when-an-object-is-eligible-for-a-garbage-collector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!