垃圾收集器理想地收集所有對象,這是程序流無法訪問的。即使此對象具有對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:增加了例子,改了一些詞讓答案更清晰。