什么是根? [英] What are the roots?
问题描述
什么是垃圾回收的根源是什么?
What are the roots in garbage collection?
我已读根作为和活的定义是您程序可以访问的任何参考的定义中的对象正在使用,它可以是一个局部变量,静态变量
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
和你最终与人
在树的根。这是活的,因为它是由一个局部变量, P
,该程序可以使用在任何时间,以指人
对象。这还要为其他对象,通过 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.
由于人
和递归连接到它的所有其他对象是活的,就不会有麻烦了,如果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
现在的人
通过 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.
这篇关于什么是根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!