Java automatically calls garbage collector, then why we need manual calls for garbage collection? When should use System.gc()
Java automatically calls garbage collector, then why we need manual calls for garbage collection?
We don't need them. Indeed, in most circumstances calling System.gc()
is harmful for application performance. See my answer to "Why is it a bad practice to call system gc" for a detailed explanation.
When should use System.gc()
If the application knows it is going into a phase where it has nothing else to do AND the user is unlikely to notice a garbage collection, then maybe it is OK call to System.gc()
in an effort to stop the user experiencing GC pauses in the future.
The downsides include:
System.gc()
typically triggers a full GC which takes significantly longer than a GC of the 'new space'.System.gc()
between "levels" in a game, you make loading the next level take longer.(There can also be legitimate reasons to call System.gc()
in unit tests, and during system debugging.)