简体   繁体   English

是什么触发了Java垃圾收集器

[英]What triggers the java Garbage Collector

I am a little confused to how garbage collection in Java works. 我对Java中的垃圾回收如何工作感到有些困惑。

I get that an object becomes eligible for garbage collection when there are no more live references to it, but what if it has references to live objects? 我得到一个对象,当不再有对其的实时引用时,就可以进行垃圾回收,但是如果它具有对实时对象的引用怎么办?

Lets say i have a collection of nodes that again references more nodes 可以说我有一个节点集合,再次引用了更多节点

List
1 -> Node a -> Node b
2 -> Node c -> Node d
3 -> Node d -> Node c
4 -> Node e
5

Now if i delete the list, node cd and e should be garbage collected. 现在,如果我删除列表,则应该对节点cd和e进行垃圾回收。 Node e has no more references to it, and node c and d have cyclical references. 节点e没有更多引用,而节点c和d具有循环引用。

But what about Node a? 但是节点a呢? Will it be garbage collected? 会被垃圾收集吗?

Will it be different whether or not node b has outside live references? 节点b是否具有外部实时引用会有所不同吗? Say if node b has a reference to it from a different place, will that make node a stay in memory? 假设节点b从另一个地方引用了它,这会使节点成为内存吗?

There is a root set of references (current local variables, static references, operand stacks of stack frames), that is considered live. 有一组根引用(当前局部变量,静态引用,堆栈帧的操作数堆栈)被认为是活动的。 Anything that is not reachable from this root set of references is eligible for garbage collection. 从此根引用根目录无法访问的所有内容都可以进行垃圾回收。

The node a is not having any reference pointing to it. 节点a没有指向它的引用。 So it is eligible for gc even if it is referring to a live object. 因此,即使它指向活动对象,也符合gc的资格。 Since node b is having live reference, it wont get gc'ed. 由于节点b具有实时引用,因此不会得到gc'ed。

It does not matter for the garbage collection of Node A if Node B has any other references to it. 如果节点B对其有任何其他引用,则对于节点A的垃圾回收无关紧要。 If Node A has no references to it, it will be garbage collected. 如果节点A没有对其的引用,则将对其进行垃圾回收。 Node B will stay, as it still has live references. 节点B将保留,因为它仍然具有实时引用。

Basically, every object that has no live references to it will be collected. 基本上,将收集没有实时引用的每个对象。 Any objects contained in those objects will be subject to the same mechanism, if there are no other references to them, they will also be garbage collected. 这些对象中包含的任何对象都将受相同的机制约束,如果没有其他引用,它们也将被垃圾回收。 If there are live references from other objects, they will stay. 如果存在来自其他对象的实时引用,则它们将保留。

The GC knows which objects are alive because it copies all live objects to a new memory area and all that are not copied are overwritten the next time. GC知道哪些对象处于活动状态,因为它将所有活动的对象复制到新的内存区域,而所有未复制的对象下次都将被覆盖。

Note that this is valid for current implementations of the GC in the Oracle VM. 请注意,这对于Oracle VM中GC的当前实现有效。 Other VMs could handle it another way. 其他VM可以用另一种方式处理它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM