在Java中,对象何时变得不可达?
在Java中,对象何时变得不可达?
在Java中,什么是不可到达对象?对象何时变得不可到达?在学习垃圾回收时,我无法理解这个概念。
有人能给出一些带有示例的想法吗?
admin 更改状态以发布 2023年5月22日
当没有任何引用变量指向它时,或者它被遗弃在一个孤立的对象(岛)中。
孤立的对象是指存在一个引用变量指向它,但是这个对象本身没有任何引用变量指向它。
class A { int i = 5; } class B { A a = new A(); } class C { B b; public static void main(String args[]) { C c = new C(); c.b = new B(); // instance of A, B, and C created c.b = null; // instance of B and A eligible to be garbage collected. }
编辑:只想指出即使A的实例有一个引用,但是因为B的实例没有对它的引用,所以A的实例现在是孤立的,它可以被垃圾回收。