Java Reference
In-Depth Information
CAUSING AND DISABLING EXPLICIT GARBAGE COLLECTION
GC is typically caused when the JVM decides GC is necessary: a minor GC will be triggered
when the new generation is full, a full GC will be triggered when the old generation is full, or a
concurrent GC (if applicable) will be triggered when the heap starts to fill up.
Java provides a mechanism for applications to force a GC to occur: the System.gc() method.
Calling that method is almost always a bad idea. This call always triggers a full GC (even if the
JVM is running with CMS or G1), so application threads will be stopped for a relatively long
period of time. And calling this method will not make the application any more efficient; it will
cause a GC to occur sooner than might have happened otherwise, but that is really just shifting the
performance impact.
There are exceptions to every rule, particularly when doing performance monitoring or bench-
marking. For small benchmarks that run a bunch of code to properly warm up the JVM, forcing a
GC before the measurement cycle may make sense. Similarly when doing heap analysis, it is usu-
ally a good idea to force a full GC before taking the heap dump. Most techniques to obtain a heap
dump will perform a full GC anyway, but there are also other ways you can force a full GC: you
can execute jcmd <process id> GC.run , or you can connect to the JVM using jconsole and
click the Perform GC button in the Memory panel.
Another exception is RMI, which calls System.gc() every hour as part of its distributed garbage
collector. That timing can be changed by setting a different value for these two system properties:
-Dsun.rmi.dgc.server.gcInterval= N and -Dsun.rmi.dgc.client.gcInterval= N . The val-
ues for N are in milliseconds, and the default value in Java 7 (which is changed from earlier re-
leases) is 3600000 (one hour).
If you end up running third-party code that incorrectly calls the System.gc() method, those GCs
can be prevented entirely by including -XX:+DisableExplicitGC in the JVM arguments; by de-
fault that flag is false .
Search WWH ::




Custom Search