How to force garbage collection in Java?

user179172 picture user179172 · Sep 26, 2009 · Viewed 339.5k times · Source

Is it possible to force garbage collection in Java, even if it is tricky to do? I know about System.gc(); and Runtime.gc(); but they only suggest to do GC. How can I force GC?

Answer

Andrew Hare picture Andrew Hare · Sep 26, 2009

Your best option is to call System.gc() which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.