对象何时有资格进行垃圾收集?

2022-01-16 00:00:00 garbage-collection java

在下面的代码中,假设 amethod 已被调用.myObject 最初引用的对象在哪一点/哪一行符合垃圾回收条件?

In the code below, given that amethod has been called. At what point/line is the Object originally referenced by myObject, eligible for Garbage Collection?

class Test {
  private Object classObject;

  public void amethod() {
    Object myObject = new Object();
    classObject = myObject;
    myObject = null;
  }
}

如果 classObjectamethod 具有 public、protected、default 或 static 的访问修饰符,它会影响对象符合垃圾收集条件的点吗?如果有,会受到怎样的影响?

And if classObject or amethod had an access modifier of public, protected, default or static, would it affect what point the Object is eligible for Garbage Collection? If so, how would it be affected?

  • 我的第一个想法是,当 Test 对象符合垃圾回收条件时,该对象符合垃圾回收条件.
  • 但话又说回来了.优化器可能知道 classObject 永远不会被读取,在这种情况下 classObject = myObject; 将被优化出来并且 myObject = null; 是它有资格进行垃圾收集的点.
  • My first thought is that the Object is eligible for Garbage Collection when the Test object is eligible for Garbage Collection.
  • But then again. The optimizer may know that the classObject is never read from in which case classObject = myObject; would be optimized out and myObject = null; is the point it is eligible for Garbage Collection.

推荐答案

对象将不会成为垃圾回收的候选对象,直到对它的所有引用都被丢弃.Java 对象是通过引用分配的,所以当你有

The object will not become a candidate for garbage collection until all references to it are discarded. Java objects are assigned by reference so when you had

   classObject = myObject;

您为堆上的同一对象分配了另一个引用.所以这一行

You assigned another reference to the same object on the heap. So this line

   myObject = null;

只去掉一个引用.要使 myObject 成为垃圾回收的候选对象,您必须拥有

Only gets rid of one reference. To make myObject a candidate for garbage collection, you have to have

  classObject = null;

相关文章