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 System.gc() why and when? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "System.gc() why and when?" Watch "System.gc() why and when?" New topic
Author

System.gc() why and when?

Gene Coetzee
Greenhorn

Joined: Apr 05, 2001
Posts: 5
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

Joined: Sep 29, 2000
Posts: 8521
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.


"JavaRanch, where the deer and the Certified play" - David O'Meara
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: System.gc() why and when?