Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java GC collect instance, while it is used by method

I have a simple question about Java GC. Some example :

Object instance = new Object();
longMethod(instance);

...

// First example
private void longMethod(Object arg) {
   Thread.sleep(1000 * 60 * 60)
   // this method works 1hr. Does it keep reference to Object and GC canot release it?
}

//Seconde example
private void longMethod(Object arg) {
  arg = null;
  Thread.sleep(1000 * 60 * 60)
  // we clear reference in method. Can GC relese Object now?
}

So what is lifecycle of "instance" in both cases? Thanks.

like image 807
Ilya Demidov Avatar asked Mar 15 '23 12:03

Ilya Demidov


2 Answers

In both cases Object instance, which is a local variable of the method that calls longMethod, holds a reference to the instance, so the GC can't release it before the method that called longMethod ends.

Note that arg = null only sets the local reference inside longMethod to null. It doesn't change the value of the instance variable in the method that called longMethod.

like image 101
Eran Avatar answered Mar 18 '23 02:03

Eran


Java is pass-by-value: setting the local variable arg in the second method to null does not mean that the local variable in the caller method is also set to reference null. Therefore, the object in the caller still has a reference pointed to it.

Consider the case where you create a new object inside the method:

private void longMethod(Object arg) {
   arg = new Object();  // Line 1
   Thread.sleep(1000 * 60 * 60);
   arg = null;  // now the object created in line 1 is eligible for GC

}

In this case, the object created using arg = new Object(); (which is different than the one created in the caller method) is eligible for GC.

And consider the case where you have this in the caller method:

Object instance = new Object();  // Line 1
longMethod(instance);   
instance = null; // now the object created in line 1 is eligible for GC (see note below)

Now the object previously created in Line 1 is also eligible for GC assuming there are no references to the object that were created inside longMethod.

like image 43
M A Avatar answered Mar 18 '23 03:03

M A