• Post Reply Bookmark Topic Watch Topic
  • New Topic

Garbage Collection  RSS feed

 
Anamika Agarwal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is a variable eligible for garbage collection when it goes out of scope?
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garabage collcetion is applied only for objects and not for variables.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vicken Karaoghlanian:
Garabage collcetion is applied only for objects and not for variables.


Quite correct. The reason is that (local) variables life on the stack, not on the heap. The stack memory is automatically released when the method is finished.
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a local variable refers to an object and the local variable goes out of scope and there are no other references to that object then the object becomes eligible for garbage collection. I suspect that might be what you were getting at with your question but then again I may just be way off the mark...

Jules
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Julian Kennedy:
If a local variable refers to an object and the local variable goes out of scope and there are no other references to that object then the object becomes eligible for garbage collection.


I am not sure that this is true. At the byte code level, all local variables have method scope, so I think that it isn't guaranteed that a reference to an object from a local variable gets lost before the containing method is finished.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
I am not sure that this is true. At the byte code level, all local variables have method scope, so I think that it isn't guaranteed that a reference to an object from a local variable gets lost before the containing method is finished.
It isn't guaranteed, and in older JVMs it doesn't happen. The Sun 1.4 JVM can garbage collect a variable as soon as it goes out of scope, though, even before the method terminates and the stack frame gets cleaned up.

- Peter
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had a feeling that was going to get stomped on when I wrote it. Thanks Ilja and Peter for the extra detail; it's always good to know.

Jules
 
Anamika Agarwal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks all for clearing my doubt
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!