MuellerDavid
MuellerDavid

Reputation: 67

How many objects are eligible for the garbage collector?

Could you please check my solution to the question: "How many objects are eligible for the garbage collector on the line (// custom code)?"

class Dog {
    String name;
}

public class TestGarbage {               
    public static void main(String[] args) { 
        Dog d1 = new Dog();                
        Dog d2 = new Dog();                
        Dog d3 = new Dog();                

        d1 = d3;                                   // line 1
        d3 = d2;                                   // line 2
        d2 = null;                                 // line 3

        // custom code
    }
}

What I know from the documenation: "The object will not become a candidate for garbage collection until all references to it are discarded."

Objects and references: (Where A, B and C are the Objects created)

d1 -> A
d2 -> B
d3 -> C
------- d1 = d3 ------
d1 -> C
d2 -> B
d3 -> C
------- d3 = d2 ------
d1 -> C
d2 -> B
d3 -> B
------- d2 = null ------
d1 -> C
d2 -> null
d3 -> B

A is eligible to delete, so we can say that there is ONLY ONE object which is eligible for the garbage collector!

Is this approach right?

Upvotes: 0

Views: 84

Answers (1)

Brian White
Brian White

Reputation: 8736

You are correct that only A, the first Dog object created, is obviously available for collection.

However, if your "custom code" does not include any references to d1, d2, or d3 then those variables could be be discarded at any time by the compiler leaving all Dog objects as GC candidates.

Upvotes: 0

Related Questions