• Post Reply Bookmark Topic Watch Topic
  • New Topic

Garbage Collection for objects created within a method.  RSS feed

 
ani pillai
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I had a question regarding when an object that has been created locally within a method call will be garbage collected. I know we can't force GC, but is it safe to assume that usually a locally created object is up for collection as soon as you return from the method call?
 
Amandeep Singh
Ranch Hand
Posts: 853
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can force GC.

yes you can safely assume, as soon as the object is out of scope. it is ready to be garbage collected. but don't assume that it will be done immediately. JVM is very clever. it takes care of everything.

Java Strength is not its language. Java's strength is JVM.
 
jack borton
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

As Ani said we can't force the garbage collector, even if we call: Using the function to call the GC does not assure that the objects are collected, It depends on the VM.

 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ani pillai wrote:is it safe to assume that usually a locally created object is up for collection as soon as you return from the method call?

Unless you use a reference to it as the return value of the method, or store a reference in any other way.
 
Birla Murugesan
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Garbage collector can remove the objects which can no longer be accessed or referenced.
 
salvin francis
Bartender
Posts: 1653
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My Belief is that
garbage collection is indeed a costly issue,

Just because objects need to be destroyed does not mean that should be done instantaneously

System.gc(); is merely a request not a command.

The JVM would probably wait [just guessing] for a batch operation rather than clearing memory after every statement block
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!