本文介绍了java - 垃圾收集器如何快速知道哪些对象不再有对它们的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Java中,如果一个对象没有任何引用,垃圾收集器会在一段时间后收回它。



但是垃圾收集器如何知道一个对象是否有与之相关的引用?



垃圾回收器是否使用某种散列表或表格?






编辑:

请注意,我不是询问gc如何工作。真的,我不是这样问的。



我特别要求 ,说明gc如何知道哪些对象是活的,哪些是死的,效率高。



这就是为什么我在我的问题中说gc保持某种类型的hashmap或set,并持续更新一个对象的引用数量

解决方案

典型的现代JVM使用几种不同类型的垃圾收集器。

用于已经存在一段时间的对象称为。它基本上涉及从已知的活对象(所谓的垃圾收集根)开始,跟随所有对象引用链,并将每个可到达对象标记为活。



完成后, sweep 阶段可以收回那些尚未标记为live的对象。



要使此过程正常工作,JVM必须知道每个对象引用在内存中的位置。这是垃圾收集器必须的条件: 精确 (这是Java的)。


I understand that in Java, if an object doesn't have any references to it any more, the garbage collector will reclaim it back some time later.

But how does the garbage collector know that an object has or has not references associated to it?

Is garbage collector using some kind of hashmap or table?


Edit:

Please note that I am not asking how generally gc works. really, I am not asking that.

I am asking specifically that How gc knows which objects are live and which are dead, with efficiencies.

That's why I say in my question that is gc maintain some kind of hashmap or set, and consistently update the number of references an object has?

解决方案

A typical modern JVM uses several different types of garbage collectors.

One type that's often used for objects that have been around for a while is called Mark-and-Sweep. It basically involves starting from known "live" objects (the so-called garbage collection roots), following all chains of object references, and marking every reachable object as "live".

Once this is done, the sweep stage can reclaim those objects that haven't been marked as "live".

For this process to work, the JVM has to know the location in memory of every object reference. This is a necessary condition for a garbage collector to be precise (which Java's is).

这篇关于java - 垃圾收集器如何快速知道哪些对象不再有对它们的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:52