Java保留周期(垃圾收集) [英] Java retain cycle (garbage collection)

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

问题描述

我知道一个保留周期(至少在Objective-C和Swift中)是两个对象声明对方的所有权(它们之间有相互引用)。在Objective-C中,我们可以通过声明其中一个 weak 来解决问题。

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

解决方案

Java垃圾收集器通过查找可达对象 - 。如果他们无法到达(如果他们没有外部对象引用),那么可以丢弃整个对象图。



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



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). 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天全站免登陆