0
votes

I have a question on eligibility of garbage collection for this piece of code.

public static void main(String[] args) {
    Object a = new Object();
    Object b = new Object();
    Object c = new Object();
    a = b;
    b = c;
    c = null;
}

I've read through a couple examples of Java garbage collection and I think I'm getting the hang of it. So what I was thinking is that after the line c = null; only c will be eligible for garbage collection because it's the only object that has discarded all references to it. Am I right here?

Thanks!

3
what is s2? there is no s2 in the code - DesirePRG
apologies I meant c fixed it - Mark
No. That object is being referenced by b now. The only object eligible is Object a = new Object(). That object was dereferenced as soon as you reassigned a with a = b. - Codebender
I see I see.. thanks everyone for clearing my misconception up! - Mark

3 Answers

5
votes

In Java, variables are not eligible for garbage collection; objects are. Variables hold references to objects but are not the objects themselves.

Let's look at your example with some sample object IDs (the internal identifiers the JVM uses to keep track of them, and not ordinarily visible):

Object a = new Object(); // id=1
Object b = new Object(); // id=2
Object c = new Object(); // id=3

You now have objects 1, 2, and 3, each referenced from a single variable: a:1, b:2, c:3. When you copy those references between variables, here's what the state looks like:

a = b;    // a:2, b:2, c:3
b = c;    // a:2, b:3, c:3
c = null; // a:2, b:3, c:null

After a = b, you've lost all references to object 1, which was originally in a, and so it immediately becomes eligible for garbage collection. Objects 2 and 3 are still reachable until the end of the block, where all of the variables fall out of scope together.

3
votes

Only a's object will be elligible for garbage collection.Take a piece of paper and draw it, and you will know.

enter image description here

0
votes

As I read from the book OCA Java SE 7

An object is marked as eligible to be garbage collected when it can no longer be accessed, which can happen when the object goes out of scope. It can also happen when an object’s reference variable is assigned an explicit null value or is reinitialized.

So, if we apply this definition, the answer will be: object a. Here I repeat object and not the reference.We must make a distinction between the object and the reference!!!