ガベージ コレクターは、理想的には、プログラム フローでは到達できないすべてのオブジェクトを収集します。このオブジェクトが 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: 例を追加し、いくつかの単語を変更して回答を明確にしました。