-1

i an not able to track where garbage collector being invoked.plz help

class Garbage01
{ 
public static void main(String args[]) 
{
    Garbage01 h = new Garbage01(); 
    h.methodA(); /* Line 6 */
} 
Object methodA() 
{
    Object obj1 = new Object(); 
    Object [] obj2 = new Object[1]; 
    obj2[0] = obj1; 
    obj1 = null; 
    return obj2[0]; 
} 
}
Sandeep vashisth
  • 1,040
  • 7
  • 20
  • 40
  • 3
    It's impossible to track where garbage collector being invoked. – johnchen902 May 08 '13 at 12:11
  • 6
    The garbage collector will run when it wants to run. There are some guarantees that it will run in certain circumstanes (before throwing an OutOfMemoryError), but other than that, you can't know when it runs, and you can't force it to run. – JB Nizet May 08 '13 at 12:12
  • *Where will be the most chance of the garbage collector being invoked?* : On completion of `main()` !!!! – AllTooSir May 08 '13 at 12:13
  • 3
    @NoobUnChained `C:\Users\JohnChen\Desktop>java -verbose:gc Garbage01` `\n` `C:\Users\JohnChen\Desktop>` No, the most chance is that garbage collector *won't* be invoked! – johnchen902 May 08 '13 at 12:17
  • @Sandeep vashisth: but *why* do you need help in tracking where the garbage collector is invoked? Maybe you need to add some more context to your problem what it is you are trying to prove / solve. – JBert May 08 '13 at 12:19

2 Answers2

2

Garbage collection in java is called automatically and it collects object which are eligible for garbage collection.

Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null.

Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.

So there is no possibility to check when garbage collector is called/invoked.

Madhusudan Joshi
  • 4,438
  • 3
  • 26
  • 42
0

Garbage collector never invoked in methodA()

because 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.

  • You might be able to say when it's _not_ going to happen, but you certainly cannot definitively say _when_ it's going to happen. – NilsH May 08 '13 at 12:16
  • The garbage collector will not be called here because a reference to the object is being maintained and returned in obj2[0] –  May 08 '13 at 12:31
  • 1
    You can say that the reference will not be garbage collected, but my point is that you can't say exactly _when_ the garbage collector will run. – NilsH May 08 '13 at 12:35