File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Performance and the fly likes runtime.gc() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Performance
Bookmark "runtime.gc()" Watch "runtime.gc()" New topic


Kee Kee moon
Ranch Hand

Joined: Dec 11, 2009
Posts: 147

Is it necessary to add the following codes into my program, or let it auto clean up. What are pros and cons.)

Runtime runtime = Runtime.getRuntime();

Thank you.

Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

No, there should never be a need to call those methods. If you've written your code correctly and provided the right parameters at JVM startup, those will have little or no effect.

In certain special cases, things might run more smoothly (fewer noticeable bumps) at the cost of slightly lower overall throughput if you explicitly invoke GC, and in certain rare cases, explicitly invoking GC might prevent an OutOfMemoryError, but I would only add it as a last resort, after first examining my design and code and reviewing my startup JVM params.
Paul Balm
Ranch Hand

Joined: Dec 13, 2008
Posts: 63
in certain rare cases, explicitly invoking GC might prevent an OutOfMemoryError

Really? I thought the JVM guarantees that no OutOfMemoryError is thrown if memory can be freed up by garbage collection?

In any case, I agree that if you have OutOfMemoryErrors, calling Runtime.gc() is never a solution. You need to look at ways to use less memory (allow objects to be garbage collected) first, then consider other options like writing rarely accessed data to disk, distributing the work over more machines or scaling up your machines (add memory).

SCJP 1.4 -- SCJD Java 2 -- OCM JEA 5
I agree. Here's the link:
subject: runtime.gc()
It's not a secret anymore!