• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object Life-cycle & Garbage Collector

 
edirg559
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ranchers:

Consider this:


Class Test {

Bar doBar () {
Bar b = new Bar();
return b;
}
}



Will object Bar eligible to garbage collection once doBar() completes (out of scope)? I know it should be, but there is a "return b" there, which confuses me.

Consider if I make lines like this:

How can the Bar object be eligible to garbage collector, while it is passing to another "newBar" reference? Isn't "newBar" right now is pointing to the same memory address (object) which was created inside the doBar() method?

Thanks,
Erik
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your intuition here is correct. If a method returns an object reference, and the caller stores that return value somewhere, then the returned object does not become eligible for GC just because the original reference went out of scope. An object can't be GC'd until there are no references left at all; no reference is special in any way, so it doesn't matter that the first one is gone, as long as a new reference is stored somewhere.
 
edirg559
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, is that means when the "doBar()" method is called by Test object, the Bar object created will not be available for GC, because it is returned (or passed to new reference) to Test object? The original Bar object is still living in the Heap and referrenced by Test object. Am I correct in this way?

Erik
 
Jass Singh
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Erik Dirgaria:
So, is that means when the "doBar()" method is called by Test object, the Bar object created will not be available for GC, because it is returned (or passed to new reference)


Correct

Originally posted by Erik Dirgaria:
The original Bar object is still living in the Heap and referrenced by Test object. Am I correct in this way?


Not so correct. The original Bar object is still living in the Heap and referrenced by newBar

Regards,
Jass
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic