File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Object Life-cycle & Garbage Collector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Object Life-cycle & Garbage Collector" Watch "Object Life-cycle & Garbage Collector" New topic
Author

Object Life-cycle & Garbage Collector

edirg559
Greenhorn

Joined: Apr 19, 2006
Posts: 19
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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.


[Jess in Action][AskingGoodQuestions]
edirg559
Greenhorn

Joined: Apr 19, 2006
Posts: 19
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

Joined: Mar 30, 2006
Posts: 52
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object Life-cycle & Garbage Collector