垃圾回收的根源是什么?
What are the roots in garbage collection?
我已将 root 的定义读为您的程序可以访问的任何引用",而 live 的定义是正在使用的对象,可以是局部变量、静态变量.
I have read the definition of root as "any reference that you program can access to" and definition of live is that an object that is being used, which can be a local variable, static variable.
我对区分根对象和活动对象之间的区别有点困惑.
I m little confused with discriminating the difference between root and live objects.
什么是根路径?根对象和活动对象如何工作?
What is path to root? How does root and live objects work?
有人可以详细说明吗?
如果您将内存中的对象视为一棵树,根"将是根节点 - 您的程序可以立即访问的每个对象.
If you think of the objects in memory as a tree, the "roots" would be the root nodes - every object immediately accessible by your program.
Person p = new Person();
p.car = new Car(RED);
p.car.engine = new Engine();
p.car.horn = new AnnoyingHorn();
有四个对象;一个人,一辆红色的汽车,它的引擎和喇叭.绘制参考图:
There are four objects; a person, a red car, its engine and horn. Draw the reference graph:
Person [p]
|
Car (red)
/
Engine AnnoyingHorn
您最终会在树的根"处找到 Person
.它是实时的,因为它被一个局部变量 p
引用,程序可以随时使用它来引用 Person
对象.这也适用于其他对象,通过 p.car
、p.car.engine
等.
And you'll end up with Person
at the "root" of the tree. It's live because it's referenced by a local variable, p
, which the program might use at any time to refer to the Person
object. This also goes for the other objects, through p.car
, p.car.engine
, etc.
由于 Person
和所有其他递归连接到它的对象都是活动的,如果 GC 收集它们会很麻烦.
Since Person
and all other objects recursively connected to it are live, there would be trouble if the GC collected them.
但是,请考虑,如果在一段时间后运行以下命令:
Consider, however, if the following is run after a while:
p.car = new Car(BLUE);
并重新绘制图形:
Person [p]
|
Car (blue) Car (red)
/
Engine AnnoyingHorn
现在 Person
可以通过 p
和蓝色汽车通过 p.car
访问,但是红色汽车或其部分可以再次访问 - 它们没有连接到活动根.可以安全地收集它们.
Now the Person
is accessible through p
and the blue car through p.car
, but there is no way the red car or its parts can ever be accessed again - they are not connected to a live root. They can be safely collected.
因此,这实际上是获取每个起点(每个局部变量、全局变量、静态变量、其他线程和堆栈帧中的所有内容)——每个根节点——并递归地跟踪所有引用以组成所有实时"列表的问题" 对象:正在使用且不适合删除的对象.其他都是垃圾,等待收集.
So it's really a matter of taking every starting point (every local variable, globals, statics, everything in other threads and stack frames) — every root — and recursively following all the references to make up a list of all the "live" objects: objects which are in use and unsuitable for deletion. Everything else is garbage, waiting to be collected.
这篇关于根源是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!