How many objects are eligible for the 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 d=new A().aob=new A();  //tricky assignement
          c=b;                      //one object eligible GC


There are two objects suitable for garbage collection, but they are difficult to understand.

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


1) In this line I will explain what it would do it

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

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


2) But what really does is (so one suitable object) WHY DO YOU LIKE?

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

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


because the assignments are right-to-left associative.

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


Can anyone explain this differently? Thanks to


source to share

3 answers

It starts from right to left. The first is executed new A()

and a new object is created. It is then assigned the field of aob

another new object A

. Finally, it d

refers to a property aob

. This means that the second object A

is eligible for garbage collection.

What is it like:

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


But the object secondA

is created inline, so there are no references to it and it is eligible for garbage collection.



In this example, what do you expect?

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


will it d

be an instance a

or an instance b


Would you expect this to be different just because you are creating inline objects?

in this example, of course, d

must be an object b

, and therefore the object is a

not referenced and can be garbage collected.



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


In Java, the assignment operator is right-associative, i.e. evaluated from right to left. But they are also in the lowest priority operator group.

So the second new operator (to the right of the second equality) is evaluated first and we get a new object A; let's say ' a . We now have:

new A().aob = a;


The trick here is to recognize operator precedence. Take a look here:

"New" operator and "." the method invocation operator has the same precedence, but their associative quality is reversed: "new" is right-associative and "." left associative.

So, the compiler first applies the new operator to the "correct operand" which is located here "A ()" (until the next operand appears). Let's call the new object b ; and we have:

A d = b.aob = a;


The compiler should now apply '.' operator first (because "." has higher precedence than "=" operator). Let's call the object denoted by 'b.aob' as c :

A d = c = a;


Finally, all the rest are assignment operators and they are right-associative (evaluated from right to left). So a is assigned to c (b.aob) and then c is assigned to d .



All Articles