垃圾收集器理想地收集程序流无法访问的所有对象。即使此对象引用了 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:添加示例,更改了一些单词以使答案更清晰。