Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many objects eligible for Garbage Collector

class A{
     A aob;
     public static void main(String args[]){
          A a=new A();
          A b=new A();
          A c=new A();
          a.aob=b;
          b.aob=a;
          c.aob=a.aob;
          A d=new A().aob=new A();  //tricky assignement
          c=b;                      //one object eligible GC
          c.aob=null;
          System.gc();
     }
}

There is two objectcs eligible for garbage collection but one is difficult to understand.

A d=new A().aob=new A();

1) This line I thing that it would make this

A d = new A().aob = new A();
          ^             ^
          O1            O2

      O1 --> O2 --> null
      ^
      |
d ----| 

2) But what really is doing is this (so one eligible object) WHY IS LIKE THIS?

A d = new A().aob = new A();
          ^             ^
          O1            O2

      O1 --> O2 --> null
             ^
             |
d -----------| 

because the assignements are associative right to left.

A d = ( new A().aob = new A() );

Could anyone explain it otherwise? Thanks

like image 816
Joe Avatar asked Dec 28 '25 16:12

Joe


1 Answers

It starts from right to left. First new A() is executed and a new object is created. Then it is assigned to the field aob of another new object A. Finally d is referencing the property aob. This means the second object A is eligible for garbage collection.

It is like:

A firstA = new A();
A secondA = new A();
secondA.aob = firstA;
A d = secondA.aob;

But the secondA object is created inline so there are no references to it and it is eligible for garbage collection.

like image 128
Petar Minchev Avatar answered Dec 30 '25 06:12

Petar Minchev