• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on Garbage Collection  RSS feed

 
Shanel Jacob
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Suppose you have the following code. When is "obj" eligible for garbage collection?

 
babu sharath
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it is not eligible for garbage collection , as it is returned by method
 
Jon Lee
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
agree with the buddy above
 
Neelesh Bodas
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question doesnot make sense. "obj" is a "(local) reference variable". What is garbage-collected are not references, but the "objects". So your question should have really been "When is the object created on such-and-such line eligible for garbage collection"

Given that, since the reference returned by the program refers to the same object that you are talking about, the object doesnot become eligible for GC when the given piece of code is getting executed.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, be clear that it is not obj that is eligible for garbage collection.
obj is a reference variable and it refers to an instance of class Integer that holds the value 5. It is that object which is going to be possibly (at some time) garbage collected when it has no references to it.

The statement objArray[0] = obj; caused a second reference to the Integer object to be made in the first element of the array.

The statement obj = null; "cuts" one of the two references leaving just the reference in the array referred to by objArray.

But then the array gets passed over to the caller of objMethod() with the reference to the Integer object still in it.

You do not know what the caller is going to do with that array and its contents. All you can say is that the Integer object is not eligible for garbage collection at the time the method returns.
 
Shanel Jacob
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah ok I get it. So because there's still one more reference pointing to the object. The object is not eligible for garbage collection.

Thank you all!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!