java GC如何清理相关的对象 [英] How does java GC clean inter related object

查看:481
本文介绍了java GC如何清理相关的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我什么会与彼此引用的对象? java的GC如何解决这个问题?如果您有对象A和B,并且以下条件成立:

$ b

解决方案


$ b

  • 引用B

  • B引用A

  • 没有其他对象引用它们中的任何一个

  • 它们不是根对象(例如,常量池中的对象)



然后,这两个对象将被垃圾收集。这被称为循环引用。



这是因为标记和清除GC将扫描并找出所有可从根对象访问的对象。如果A和B在没有任何外部参考的情况下相互引用,则标记和扫描GC将无法将它们标记为可到达,因此将被选作GC的候选。



有许多不同的标记和扫描实现(天真标记和扫描,三色等)。但基本的想法是一样的。如果无法通过直接/间接引用从根目录访问对象,则会收集垃圾。


Could anyone please tell me what will be with objects that refer to each other? How does java's GC resolve that issue? Thanks in advance!

解决方案

If you have object A and B, and if the following conditions hold:

  • A references to B
  • B references to A
  • No other objects reference to any one of them
  • They are not root objects (e.g. objects in the constants pool etc)

then, these two objects will be garbage collected. This is called "circular reference".

This is because the mark-and-sweep GC will scan and find out all the objects that are reachable from the root objects. If A and B reference each other without any external reference, the mark-and-sweep GC won't be able to mark them as reachable, hence will be selected as candidates for GC.

There are a number of different mark-and-sweep implementations (naive mark-and-sweep, tri-colour etc). But the fundamental idea is the same. If an object cannot be reached from the root by direct/indirect references, it will be garbage collected.

这篇关于java GC如何清理相关的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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