简体   繁体   English

内存中松散的对象“链”上的Java GC

[英]Java GC on an object-“chain” loose in memory

During runtime, object object1 is referring to object object2 . 在运行时,对象object1引用对象object2 However, object1 has no reference to it. 但是, object1没有引用它。

In this case, would object1 , and thus object2 be collected by GC? 在这种情况下,将object1 ,因而object2被GC回收?

If yes -- object2 has a reference to it and is being "automatically" removed from the memory in this case. 如果是,则object2具有对其的引用,在这种情况下,将“自动”从内存中删除该对象。

If no -- than that would be because object2 has a reference to it (from object1 ) and that's why it isn't collected. 如果否,那是因为object2引用了它(来自object1 ),这就是为什么不收集它的原因。 But then object1 is loose, and it should be collected. 但是然后object1松散了,应该将其收集起来。

How does the GC work on these? GC如何处理这些? Does it collect object1 first cause it's "loose" in memory, then, in the next round, it collects object2 cause it is loose now that it isn't referenced. 它是否首先收集object1导致其在内存中“松动”,然后在下一轮中收集object2导致其松动(因为现在未对其进行引用)。 Or it collects object1 and object2 both when it's on collecting object1 ? 或者,它收集object1object2都当它是在收集object1

Another case that might be is: object1 is running a process. 可能的另一种情况是: object1正在运行一个进程。 So, GC doesn't touch it, and object2 , being references from object2 , remains in memory as well. 因此,GC不会碰它,而object2 (来自object2引用)也保留在内存中。 But this wouldn't hold-- from what i know, GC doesn't look up whether the object has CPU time assigned to it(?), it just goes by the references and whenever there's no reference to it, removes the object from the heap. 但这不会成立-据我所知,GC不会查询对象是否分配了CPU时间(?),它只是通过引用进行的,只要没有引用就会从中删除对象堆。

How does GC work on these two objects-- object1 & object2 in this case? 如何在GC的工作这两个objects-- object1object2在这种情况下?

//======================================== // =======================================

EDIT: 编辑:

This is a Q on the specifics of GC. 这是关于GC细节的Q。 Anyone can look up "GC collects objects that aren't referenced." 任何人都可以查找“ GC收集未引用的对象”。

TIA. TIA。

您正在混合对象和引用,只要堆中的任何对象都有对其的实时引用,它将不会被GC化

How does Java Garbage Collection work with Circular References? Java垃圾收集如何与循环引用一起使用? gives the answer -- both object1 and object2 are collected since "they aren't reachable from a GC root". 给出了答案-收集了object1object2 ,因为“它们无法从GC根目录访问”。 It also implies that they both are collected at once-- not object1 first and then object2 which is eventually loose. 这也意味着它们都是一次被收集的-不是首先是object1 ,然后是最终松散的object2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM