简体   繁体   中英

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

During runtime, object object1 is referring to object object2 . However, object1 has no reference to it.

In this case, would object1 , and thus object2 be collected by GC?

If yes -- object2 has a reference to it and is being "automatically" removed from the memory in this case.

If no -- than that would be because object2 has a reference to it (from object1 ) and that's why it isn't collected. But then object1 is loose, and it should be collected.

How does the GC work on these? 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. Or it collects object1 and object2 both when it's on collecting object1 ?

Another case that might be is: object1 is running a process. So, GC doesn't touch it, and object2 , being references from object2 , remains in memory as well. 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.

How does GC work on these two objects-- object1 & object2 in this case?

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

EDIT:

This is a Q on the specifics of GC. Anyone can look up "GC collects objects that aren't referenced."

TIA.

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

How does Java Garbage Collection work with Circular References? gives the answer -- both object1 and object2 are collected since "they aren't reachable from a GC root". It also implies that they both are collected at once-- not object1 first and then object2 which is eventually loose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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