问题描述
我知道在 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?
垃圾收集器是否使用某种 hashmap 或表?
Is garbage collector using some kind of hashmap or table?
请注意,我不是在问 gc 的工作原理.真的,我不是在问这个.
Please note that I am not asking how generally gc works. really, I am not asking that.
我要特别地询问 gc 如何高效地知道哪些对象是活动的,哪些是死的.
I am asking specifically that How gc knows which objects are live and which are dead, with efficiencies.
这就是为什么我在我的问题中说 gc 维护某种 hashmap 或集合,并不断更新对象的引用数量?
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?
推荐答案
典型的现代 JVM 使用几种不同类型的垃圾收集器.
A typical modern JVM uses several different types of garbage collectors.
一种常用于已存在一段时间的对象的类型称为 Mark-and-Sweep.它基本上涉及从已知的活动"对象(所谓的垃圾收集根)开始,跟踪所有对象引用链,并将每个可达对象标记为活动".
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".
完成此操作后,sweep 阶段可以回收那些尚未标记为活动"的对象.
Once this is done, the sweep stage can reclaim those objects that haven't been marked as "live".
为了让这个过程正常工作,JVM 必须知道每个对象引用在内存中的位置.这是垃圾收集器精确(Java 就是这样).
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 - 垃圾收集器如何快速知道哪些对象不再引用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!