0

I am not sure if I have understood the behaviour of garbage collector completely, therefore I am posing this question based on a previous question.

In this program:

class A {
    Boolean b;
    A easyMethod(A a){
       return new A();
    }
    public static void main(String [] args){
        A a1 = new A();
        A a2 = new A();
        A a3 = new A();
        a3 = a1.easyMethod(a2);
        a1 = null;
        // Some other code 
    }
} 

how many objects would be eligible for garbage collection? I think that although a3 never becomes null, the first object (new A()) assigned to it should also be garbage-collected, as no references still point to it. Am I right? I think hence that the correct answer would be again 2 objects. What is true actually?

Community
  • 1
  • 1
arjacsoh
  • 8,932
  • 28
  • 106
  • 166
  • 3
    Don't base your question on another question, this is not a discussion thread. Post the complete code of relevance here. – Marko Topolnik Nov 13 '12 at 21:53
  • 1
    The compiler may well discard any variables and assignments which it finds will never be read again during their potential lifetime. So, an object assigned to a variable in your code is not automatically referenced, or 'reachable', thereafter at runtime, which means that the object may be eligible for collection immediately after its constructor was executed. – JimmyB Nov 13 '12 at 21:56

2 Answers2

2

I think that although a3 never becomes null, the first object (new A()) assigned to it should also be garbage-collected, as no references still point to it. Am I right? I think hence that the correct answer would be again 2 objects.

Yes, this is exactly right. a3 originally points to one instance of A, but after that variable is reassigned to point to a different instance, there is no longer any way to reach the original instance, so said original instance becomes eligible for garbage collection.

ruakh
  • 175,680
  • 26
  • 273
  • 307
2

Yes, you are right.

a1 = <instance 1>
a2 = <instance 2>
a3 = <instance 3>
a3 = <instance 4> //as a returned value
a1 = null

So instance 1 and instance 3 are no longer referenced and thus may be collected.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58