Ismail Rana Ismail Rana - 3 months ago 33
Java Question

Issue with Garbage Collection

I have code some what like

class HappyGarbage01
public static void main(String args[])
HappyGarbage01 h = new HappyGarbage01();
h.methodA(); /* Line 6 */
Object methodA()
Object obj1 = new Object();
Object [] obj2 = new Object[1];
obj2[0] = obj1;
obj1 = null;
return obj2[0];

Will the most chance of the garbage collector being invoked be after line 9 or 10?


The garbage collector won't be invoked after line 9 because the reference to obj1 is stored in obj2[0]. The Object obj1 still exists on the heap and can be accessed by an active thread through the reference stored in obj2[0].

Rather the garbage collection takes place after line 6. Garbage collection takes place after the method has returned its reference to the object. The method returns to line 6, there is no reference to store the return value. So the answer should be after line 6.