T8Z
T8Z

Reputation: 691

Confused about garbage collection

In the following code how many objects are eligible for garbage collection after executing line 7? In my opinion 1 object that is z is eligible. Is is right?

public class Tester 
{ 
  public static void main(String[] args) 
  {

    Integer x = new Integer(3000);   
    Integer y = new Integer(4000);   
    Integer z = new Integer(5000);

    Object a = x;   
    x = y;  
    y = z;
    z = null; //line 7 
   }
}

Thank you very much.

Upvotes: 2

Views: 135

Answers (4)

paxdiablo
paxdiablo

Reputation: 882716

Don't confuse a reference with an object. The object is the actual item that has been created, the reference is simply a name that refers to it.

You've created three objects, let's call them 3000, 4000 and 5000. You've also set up references as follows:

Ref    Object
---    ------
 x  ->  3000
 y  ->  4000
 z  ->  5000

After the assignments, you end up with:

Ref    Object
---    ------
 a  ->  3000
 x  ->  4000
 y  ->  5000
 z

Hence none of the objects are subject to garbage collection. Every single one still has a reference to it.


By way of contrast, if you were to remove the line:

Object a = x;   

then the assignments would then result in:

Ref    Object
---    ------
        3000
 x  ->  4000
 y  ->  5000
 z

and the object we called 3000 would be eligible for garbage collection, since you no longer have any way to access it.


And, as an aside, you may want to consider the fact that one of the major reasons automated garbage collection was created was to make these sorts of questions moot :-) Generally (though there are of course exceptions), you shouldn't need to worry about what objects are subject to collection.

Upvotes: 8

Abimaran Kugathasan
Abimaran Kugathasan

Reputation: 32488

None of the objects are eligible for Garbage Collections.

Every object has a live references. z is not an Object, it's just a reference. You have moved the references only.

Upvotes: 2

Zeeshan
Zeeshan

Reputation: 12431

z won't be eligible for GC at line 7. It is because in line 6, y is refrencing the object which was previously refrenced by z. So even thought you have made z=null, y is still refrencing the object created in the heap ie. new Integer(5000);

Upvotes: 1

x, y and z aren't objects - they are references to objects.

Informally, any object is eligible for garbage collection when there's no way you could possibly ever access it any more. After running this code, x refers to the 3000 object, y refers to the 4000 object, and z refers to the 5000 object. The 3000 object cannot be collected, because you could use it, e.g. System.out.println(a);. The 4000 object cannot be collected, because you could use it through x, e.g. System.out.println(x);. The 5000 object cannot be collected, because you could use it through z.

After main returns, all of those objects are eligible for garbage collection, because you can't access them after that.

Upvotes: 1

Related Questions