在Java中,对象何时变得不可达?

71 浏览
0 Comments

在Java中,对象何时变得不可达?

在Java中,什么是不可到达对象?对象何时变得不可到达?在学习垃圾回收时,我无法理解这个概念。

有人能给出一些带有示例的想法吗?

admin 更改状态以发布 2023年5月22日
0
0 Comments

当没有更多的引用指向一个对象时,或这些引用自身来自不可达对象时,该对象就是不可达的。\n\n

Integer i = new Integer(4);
// the new Integer object is reachable  via the reference in 'i' 
i = null;
// the Integer object is no longer reachable. 

0
0 Comments

当没有任何引用变量指向它时,或者它被遗弃在一个孤立的对象(岛)中。

孤立的对象是指存在一个引用变量指向它,但是这个对象本身没有任何引用变量指向它。

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的实例现在是孤立的,它可以被垃圾回收。

0