Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Garbage Collection on method arguments (from Enthuware)

 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is from Enthuware (Test 3, Question 30)


After which line will the object passed to the method getObject() be eligible for garbage collection?

public void getObject(Object a)
{
Object c, b = new Object(); //1
//do something with a
c = b; //2
a = c;//3
b = a = null; //4
c = null;
}

The answer provided is never, citing the fact that the object pointed to by the method parameter a must have been created outside and thus there must be an external reference to it.

But I think that if you call the method this way:

getObject(new Object()); // No intervening reference

The object will be eligible for GC at line //3.

Does this sound reasonable?

Thanks.
 
Brian Legg
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still think that would be considered an outside reference and would not be eligable for garbage collection until after the method completed. Wouldn't the compiler create the new Object with no named reference and then pass it into the method, wait for the method to complete, then you would lose the reference to it?
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Brian,

I just ran a test and it seems that the argument method can indeed be garbage collected before the method returns:

 
Devaka Cooray
ExamLab Creator
Marshal
Pie
Posts: 4259
227
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice demonstration Ruben.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Devaka. Maybe I learned something from your great ExamLab examples.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic