This question already has an answer here:
- Interview question: Objects eligible for garbage collection 7 answers
When is any particular object eligible for garbage collection? And which are the parameters that comes into consideration which deciding this?
MyClass mc = new MyClass(); mc.myMethod(); //line1 mc=null; //line2 mc=new object(); //line3 mc.myMethod(); //line4 mc=null; //line5
In this case, when mc object is eligible for garbage collection?
This decission is taken by the garbage collector itself, the condition for an object to be collected is made upon the number of references to it. So if an object does not have any references it becomes candidate to collection.
That does not mean that it is inmediatelly collected, just a candidate to collection. The object collection is governed by the generations mechanism:
An object is considered garbage when it can no longer be reached from any pointer in the running program. The most straightforward garbage collection algorithms simply iterate over every reachable object. Any objects left over are then considered garbage. The time this approach takes is proportional to the number of live objects, which is prohibitive for large applications maintaining lots of live data.
Concerning your code, the object created in the first line
MyClass mc = new MyClass(); becomes a candidate to collection right after the execution of the third one
Following the same pattern, the new object created at
line3 (I don't think however that line makes what you think it does: Shouldn't that line be
mc = new MyClass();?) becomes a candidate after the execution of line 5.
Note that even though you remove
line2, the first object will be elegible for collection because it is not referenced any longer.