本文介绍了什么时候该对象符合垃圾收集要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,已经调用了 amethod 。在什么点/行是最初由 myObject 引用的对象,符合垃圾收集条件?

  class Test {
private Object classObject;

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


如果 classObject amethod 有一个public,protected,default或static的访问修饰符,它会影响对象符合垃圾收集的条件吗?如果是这样,它将如何受到影响?


  • 我的第一个想法是,当Test对象符合条件时,该对象符合垃圾收集条件垃圾收集。

  • 但是再次。优化器可能知道classObject永远不会被读取,在这种情况下, classObject = myObject; 会被优化,并且 myObject = null; 是符合垃圾收集条件的点。 该对象不会成为垃圾收集的候选人,直到全部引用它为止。 Java对象是通过引用分配的,所以当你有

      classObject = myObject; 

    您将另一个引用指派给堆上的同一对象。所以这一行

      myObject = null; 

    只能删除一个引用。要使 myObject 成为垃圾收集的候选者,您必须具有

      classObject = null; 


    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;
      }
    }
    

    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?

    • 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.

    解决方案

    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;
    

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

      classObject = null;
    

    这篇关于什么时候该对象符合垃圾收集要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 09:33