What triggers the java Garbage Collector

I am a little confused to how garbage collection in Java works.

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. Node e has no more references to it, and node c and d have cyclical references.

But what about Node a? Will it be garbage collected?

Will it be different whether or not node b has outside live references? Say if node b has a reference to it from a different place, will that make node a stay in memory?


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. So it is eligible for gc even if it is referring to a live object. Since node b is having live reference, it wont get gc'ed.


It does not matter for the garbage collection of Node A if Node B has any other references to it. If Node A has no references to it, it will be garbage collected. Node B will stay, as it still has live references.

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.

Note that this is valid for current implementations of the GC in the Oracle VM. Other VMs could handle it another way.

链接地址: http://www.djcxy.com/p/19886.html

上一篇: 线程作为GC根

下一篇: 什么触发了Java垃圾收集器