3 Replies Latest reply: Jul 23, 2012 1:01 PM by 804628 RSS

    Nested object reference after garbage collection

    804628
      I have a question about how GC works.

      Assume I have a Class A which has a reference to class B inside it. I create a object of class B and assign to member variable of class A.
      Now when obja is no longer needed, I set it null. And when GC runs, the object will be removed from memory. But should I also need to explicitly set objb to null. If i don't set it, will it also get garbage collected when obja is being removed from memory?
      public class ClassA {
      
      private ClassB objB = new ClassB();
      
      private static void main(String args[]) {
      
      ClassA obja = new ClassA();
      ....
      ....
      
      obja = null;
      
      .....
      
      }
      }
        • 1. Re: Nested object reference after garbage collection
          sabre150
          801625 wrote:
          But should I also need to explicitly set objb to null.
          No.
          If i don't set it, will it also get garbage collected when obja is being removed from memory?
          If there are no other references outside of classA to the object referenced by objB (in your case an instance of ClassB) then it will be garbage collected.

          Note - the only time one needs to set a reference to null is if one wants the object it references to be eligible for GC before the reference goes out of scope. There is a slight complication to this - depending on the JVM implementation, if a reference is defined in a block internal to a method then even though it goes out of scope when execution goes out of the block anything it references may not be eligible for GC until the method exits.
          • 2. Re: Nested object reference after garbage collection
            EJP
            It doesn't depend on the JVM implementation actually, it is a function of the bytecode. There is no bytecode for an inner }. All stack space required to execute a method is allocated at method entry and popped at method exit. So whatever the JVM implementation, it cannot tell that a variable has gone out of scope EXCEPT when a stack slot is reused, which is basically equivalent to setting the variable to null. This happens like so:
            {
                Object a;
            }
            Object b; // reuses the stack slot of a, if the compiler has any brains at all.