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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With