4

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Consider a call longMethod(new Object());. The caller has no way to access the object whose reference was passed to longMethod.
@PatriciaShanahan That's a different question. I think the GC will be able to release the instance in this case for the second example, since there won't be any references left to that object.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.