Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

System.gc() why and when?

 
Gene Coetzee
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've attended the Sun Java Programming course about four months ago. During the course, the instructor mentioned that there is no way to "force" garbage collection in Java. Further studies however led me to the System.gc() method... My understanding is that by calling this method, Java's garbage collection will be "forced"??
My question: Why and when would one use this method? Isn't Garbage collection taken care of automatically?
Thanks!
- Gene.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling gc() just SUGGESTS to the system that this might be a good time to do some clean up. There is NO WAY in java to force garbage collection.
From http://java.sun.com/docs/books/tutorial/essential/system/garbage.html

Running the Garbage Collector
You can ask the garbage collector to run at any time by calling System's gc method:
System.gc();
You might want to run the garbage collector to ensure that it runs at the best time for your program rather than when it's most convenient for the runtime system to run it. For example, your program may wish to run the garbage collector right before it enters a compute or memory intensive section of code or when it knows there will be some idle time.
Note that the garbage collector requires time to complete its task. The amount of time that gc requires to complete varies depending on certain factors: How big your heap is and how fast your processor is, for example. Your program should only run the garbage collector when doing so will have no performance impact on your program.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic