本文介绍了Java垃圾收集如何与循环引用一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,Java中的垃圾回收会清除一些对象,如果没有其他东西指向该对象。



我的问题是,如果我们有像这样:

  class Node {
public object value;
下一个公共节点;
public Node(object o,Node n){value = 0; next = n;}
}

//...some代码
{
节点a =新节点(a,null),
b =新节点(b,a),
c =新节点(c,b);
a.next = c;
} //结束范围
//...other代码

a , b 和 c 应该被垃圾收集,但它们都被其他对象引用。



Java垃圾回收如何处理这个问题? (或者它只是一个内存泄漏?)

解决方案

Java的GC认为对象垃圾,如果它们无法通过链从垃圾收集根开始,因此这些对象将被收集。即使对象可能指向彼此以形成一个循环,但如果它们从根目录切断,它们仍然是垃圾。



请参阅关于无法访问的对象的部分附录A:中有关垃圾收集的真相血淋淋的细节。


From my understanding, garbage collection in Java cleans up some object if nothing else is 'pointing' to that object.

My question is, what happens if we have something like this:

class Node {
    public object value;
    public Node next;
    public Node(object o, Node n) { value = 0; next = n;}
}

//...some code
{
    Node a = new Node("a", null), 
         b = new Node("b", a), 
         c = new Node("c", b);
    a.next = c;
} //end of scope
//...other code

a, b, and c should be garbage collected, but they are all being referenced by other objects.

How does the Java garbage collection deal with this? (or is it simply a memory drain?)

解决方案

Java's GC considers objects "garbage" if they aren't reachable through a chain starting at a garbage collection root, so these objects will be collected. Even though objects may point to each other to form a cycle, they're still garbage if they're cut off from the root.

See the section on unreachable objects in Appendix A: The Truth About Garbage Collection in Java Platform Performance: Strategies and Tactics for the gory details.

这篇关于Java垃圾收集如何与循环引用一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 02:30