[英]At what line can this object be considered to be garbage collected. Java
So my understanding is at line 1, a new object is created and it is referenced by obj. 因此,我的理解是在第1行,创建了一个新对象,它由obj引用。 At line 2, obj is referencing to another new object. 在第2行,obj引用了另一个新对象。 so the object which we created at line 1 is eligible for garbage collection because it is not referenced by any instance. 因此我们在第1行创建的对象可以进行垃圾回收,因为任何实例均未引用该对象。 But the answer from test question is at line 3. Reason? 但是测试问题的答案在第3行。原因? Is the answer correct? 答案正确吗?
Object obj = new Object(); //line 1
obj = new Object(); //line 2
obj = null; //3
Edit: it is asking when the object created at line 1 can be eligible for garbage collection. 编辑:询问在第1行创建的对象何时可以进行垃圾收集。
In the real world this question (as posed by the title) has no clear answer. 在现实世界中,这个问题(由标题引起)没有明确的答案。
I know it's supposed to be an academic question with a simple answer, but there are so many assumptions to make that I could rule-lawyer you any answer you want into existence. 我知道这应该是一个带有简单答案的学术性问题,但是有很多假设可以使我可以对想要存在的任何答案进行法律裁决。
Even if we don't pull any rabbits out of our hat the answer would still depend on whether "at line X" means before or after the execution of that 即使我们没有从帽子中拉出任何兔子,答案仍将取决于“在第X行”是指执行该命令之前还是之后
The garbage collector is checking for live objects and discarding anything that is not. 垃圾收集器正在检查活动对象,并丢弃不存在的任何对象。 When you create obj
, you define it's type because that allows the compiler to know how much space to allot for that address, because something of Type Object
will exist there. 创建obj
,要定义它的类型,因为它使编译器知道要为该地址分配多少空间,因为Type Object
将在那里存在。 When the second line executes, new is creating an entirely new instance of the object and you are assigning its address to obj
. 当第二行执行时,new将创建该对象的全新实例,并且您将其地址分配给obj
。 So after reassigning obj
to reference a new object, the old one still exists, but is no longer referenced. 因此,在将obj
重新分配为引用新对象之后,旧对象仍然存在,但不再被引用。 It would potentially be marked for collection as it occupies space in the heap, but is no longer active. 它可能会被标记为要收集,因为它占用了堆中的空间,但是不再处于活动状态。 The same happens with line 3, except, as mentioned previously, you are assigning it an address of null
, and no new object is being created. 第3行也一样,除了前面提到的,您要为其分配的地址为null
,并且没有创建新对象。 So what used to be referenced by obj
are now dead objects and the garbage man takes them away. 因此,以前由obj
引用的obj
现在是死对象,而垃圾回收人员将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.