Java Programming - Garbage Collections - Discussion

2. 

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]; 
    } 
}
Where will be the most chance of the garbage collector being invoked?

[A]. After line 9
[B]. After line 10
[C]. After line 11
[D]. Garbage collector never invoked in methodA()

Answer: Option D

Explanation:

Option D is correct. 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 garbage collection takes place after line 6.

Option A is wrong. 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].

Option B is wrong. Because it is only one of the references to the object obj1, the other reference is maintained in obj2[0].

Option C is wrong. The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0].


Sukanya said: (Jun 24, 2012)  
What mean by garbage collection ?

Basha said: (Sep 24, 2012)  
Garbage collection is a one of the program in Jvm.I take the responsibel to remove the unnecessory object form memory. The garbage collection call the finalize() method before removing the object form jvm's memory.

But we can not controll the grabage collecion. If necessory the jvm invoke to the garbage collecion to maintain the memory management. But we does not give the gaurenty when the jvm invoke the garbage collection. But we can give the request to jvm to invoke the garbage collection by calling gc() that is available in System or Runtime class.

Shiva said: (Nov 23, 2016)  
Objects are eligible for GC when they have no references.

Here, Garbage collector never collects an object in the main method and even in method A since there is no object that has no reference.

You can understand that new obj1() has to reference from the array.

Craig Mautner said: (May 19, 2017)  
At the completion of methodA() obj2 is eligible for garbage collection. There are no more references to it.

Rohit said: (Jun 8, 2019)  
Option A is correct as the garbage collector will be called in line 9 as the object to which obj1 was referencing, is no longer referenced by anything as now obj2 is referencing the object of obj1.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.