First Things First: DO NOT CALL THE GC EXPLICITLY
Except if you have a very good reason for it. And even if you think you do, you probably don't.
The GC Knows What It's Doing (most of the time...)
If you kept reading, I'm assuming you have a really awesomely good (albeit probably twisted) reason to attempt to screw around with the GC, even though it is very likely to be a lot clever than you are at determining when it should collect memory. Also, keep in mind that by calling it explicitely you confuse it and screw up its heuristics, so it gets less clever than it was before. All because you attempted to outsmart it.
The GC Doesn't Always Care About What You Say
If you do this for a very good reason, or in a case where you really want to ensure that you start an intensive code section with the best memory state possible, you need to know this probably won't work: calls to System.gc()
do not guarantee a garbage collection to take place, as mentioned by its Javadoc (emphasis mine):
Calling the gc method suggests that the Java Virtual Machine expend effort
toward recycling unused objects.
Other Recommendations
Hunt Down and Kill (Bad) Explicit GC
- turn on
-XX:+DisableExplicitGC
(if your JVM supports it) to prevent those crazy calls of doing any harm (credit to Fredrik in the comments)
- look with your favorite IDE or
grep
for calls to System.gc()
and its equivalents and get rid of them.
Find Another Way
See Grooveek's answer for other useful suggestions (like using WeakReference
s).
Experiment with Other GCs and Fine-Tune Your VM for Your App
Depending on your use case, maybe experimenting with other GC implementations might help: CMC, G1, ParallelGC, etc... If you want to avoid "stalls", I have had very good results with G1 since its introduction in the latest Java SE 6 updates and since the Java 7 release, running intensive enterprise applications for long-running periods.
Just be aware that JVM tuning is a very complicated art.
Further Reading
You can flip through these for a lot more details:
* Use with care: sometimes not perfectly up-to-date, doesn't document everything, and lists a lot of experimental features, or HotSpot-only features.