Java 是否嵌套 Class 实例防止外部 Class 的 GC
Java Does Nested Class Instance Prevent GC of Outer Class
假设 Outer
在某处实例化,一段时间后没有对它的引用。 inner
中对 Outer
实例的隐式引用是否会阻止 GC 运行,或者它是否是 "special" 引用?
public class Outer {
private class Inner extends Something {}
private Inner inner = new Inner();
}
如果 Outer
的实例无法从 GC root 访问,则示例代码中对 Inner
实例的引用不会阻止垃圾收集器释放 [=11] 的内存=] 使用。
考虑这张图:
Stack of main thread public static void main(String[] args) {
| Outer outer = new Outer();
v
Outer<--\
|\ |
v \---/
Inner
Stack of main thread outer = new Outer();
|
v
Outer<--\
|\ new|
v \---/
Inner
Outer<--\ // a reference to the Outer from the Inner
|\ old| // doesn't change the fact that the Outer
v \---/ // can't be reached from a GC root.
Inner // Thus the old Outer is eligible for collection (dead)
假设 Outer
在某处实例化,一段时间后没有对它的引用。 inner
中对 Outer
实例的隐式引用是否会阻止 GC 运行,或者它是否是 "special" 引用?
public class Outer {
private class Inner extends Something {}
private Inner inner = new Inner();
}
如果 Outer
的实例无法从 GC root 访问,则示例代码中对 Inner
实例的引用不会阻止垃圾收集器释放 [=11] 的内存=] 使用。
考虑这张图:
Stack of main thread public static void main(String[] args) {
| Outer outer = new Outer();
v
Outer<--\
|\ |
v \---/
Inner
Stack of main thread outer = new Outer();
|
v
Outer<--\
|\ new|
v \---/
Inner
Outer<--\ // a reference to the Outer from the Inner
|\ old| // doesn't change the fact that the Outer
v \---/ // can't be reached from a GC root.
Inner // Thus the old Outer is eligible for collection (dead)