垃圾收集器理想地收集所有对象,这是程序流无法访问的。即使此对象具有对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:增加了例子,改了一些词让答案更清晰。