How does Java garbage collector deals with circular references when their access path is broken?

ぃ、小莉子 提交于 2019-12-07 22:38:10

问题


I just want someone explain it to me that how does GC discover that those memory blocks (pictured in red area) are garbage when their reference count is more that 0 but they are practically inaccessible?


回答1:


There's set of "root objects" which are considered always accessible: e.g., Thread references, static variables, class references. If some object can not be reached via link of references from these root objects, it considered to be available for GC, even if there are some references to that object.




回答2:


GarbageCollector works based on Java Memory Model. In java available application memory is divided in two parts: Heap and Stack. A object is stored in heap memory and can be accessed by 2 ways :-

1) Object can have reference variable which is stored in stack memory. In this case object can be directly accessed by using it's reference variable.

2) Object can be contained by any other object and would not have any reference in stack memory. In this case this object can be accessed only by using that container object. So if container object is garbage collected then this object must be eligible for garbage collection.

While doing GarbageCollection GarbageCollector checks whether a object is accessible directly or indirectly by any reference available in stack if it is then it won't collect this object else it do collect it.




回答3:


The details of the GC algorithm are implementation dependent in Java, so it depends on your VM. But most VMs do not use reference counting. The official VM even has several configurable algorithms available. So it is hard to generalize about this.



来源:https://stackoverflow.com/questions/8895618/how-does-java-garbage-collector-deals-with-circular-references-when-their-access

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