Java如何解决垃圾收集中的保留周期? [英] How does Java solve retain cycles in garbage collection?

查看:149
本文介绍了Java如何解决垃圾收集中的保留周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道保留周期(至少在Objective-C和Swift中)是两个对象声称彼此拥有(他们互相引用)。在Objective-C中,我们可以通过声明其中一个 weak 来解决问题。



根据我的阅读和理解,Java GC不受保留周期的影响,我们不必担心参考。它是如何解决的?

解决方案

Java垃圾收集器通过查找可达对象来工作 - 从根目录开始对象树。如果无法访问它们(如果它们没有外部对象引用),则可以丢弃整个对象图。



基本上它只是从根遍历树(s) )叶节点并标记它遇到的所有对象。未被堆中标记对象占用的任何内存都被扫描(标记为空闲)。这称为



这不能轻易地在 objective-c 因为它使用引用计数,而不是标记和扫描哪些有它的缺陷



没有保留周期的原因是因为如果它们没有链接到任何地方的树,它们就不会被标记并且可以被丢弃。


I know that a retain cycle (at least in Objective-C and Swift) is when two objects claim ownership of one another (they have references to each other). And in Objective-C we can solve the issue by declaring one of them weak.

From what I have read and understood, the Java GC is not affected by retain cycles, and we do not have to worry about weak references. How does it solve it?

解决方案

The Java garbage collector works by looking for "reachable" objects - from the root(s) of the object tree. If they can't be reached (if they have no outside object references) then entire object graphs can be discarded.

Essentially it just just traverses the tree from root(s) to leaf nodes and marks all objects it encounters. Any memory not taken up by marked objects in the heap is swept (marked as free). This is called mark and sweep. img src

This can't be done easily in because it uses reference counting, not mark and sweep which has it's flaws

The reason there can be no retain cycles is because if they aren't linked to the "tree" anywhere, they aren't marked and can be discarded.

这篇关于Java如何解决垃圾收集中的保留周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆