这个问题是在学习LinkedList数据结构时出现的。假设每个 Link(或节点)都由一个包含两个字段的对象表示,data 和 next 指向下一个链接。如果我想删除一个特定的节点,显然我会更新前一个链接的 next 字段。但是我是否应该将已删除链接的 next 字段设置为空,以确保它会被垃圾收集器回收?
如果我的描述不清楚,我会尝试概括(或简化)我的问题。假设类 A 的对象 a1 有一个字段,该字段引用同一类的另一个对象 a2。如果没有对对象 a1 的引用,它是否符合垃圾收集器的条件?或者我们必须明确地将 a1 中的引用字段设置为 null ? (不用关心对象a2,除了a1中的引用域外,还有其他对它的引用)。
最佳答案
垃圾收集器理想地收集程序流无法到达的所有对象。即使此对象引用了 JVM 中的所有内容。
如果所有正在运行的程序线程不包含对它的任何直接或间接引用,则对象变得不可访问。
直接引用看起来像这样:
void main(String... args){
Object a = new Object(); // <- from here main thread of program
// has reference to object `a`
...
}
间接引用看起来像这样:
void main(String... args){
List b = new ArrayList();
b.add(new Object()); // <- here you can't access object by typing `a`
// as in previous example, but you can get access with `b.get(0);`
// so that object can be accessed indirectly -> it is reachable.
}
它还可以正确处理大对象孤岛的情况,这些对象相互引用,但都不能再从程序流中访问到。
MyClass a = new MyClass();
MyClass b = new MyClass();
a.field = b;
b.field = a;
// at this point a and b are reachable so they cannot be collected
b = null;
// at this point b's object is reachable indirectly through `a.field`
// so neither a nor b can be collected
a = null;
// at this point you cannot reach neither a nor b
// so a and b can be garbage collected,
// despite the fact that a is referenced by b and vice versa
UPD:添加了示例,更改了一些词以使答案更清楚。
关于java - Java垃圾收集器会回收包含对其他对象的引用的非引用对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15764939/