Calling System.gc( ) explicitly?

The best way, in my opinion, to think of the System.gc() method is as a “hint” to the VM that garbage collection should run. That said, much like a large percentage of “optimizations” people think they are performing, it’s usually best to just let the system take care of things on its own. Systems are evolving etc, etc, etc. There are still some instances where the developer may actually know better and the use case for it is probably very similar to why some code is still written in assembly (most of the time, the compiler is better, but in a few instances — or with a few developers — humans can actually write more efficient code).

One example I’ve seen used in the past to justify its existence is in the event that a large number of objects were allocated and you as the developer know the instant they are no longer going to be used. In that case, you may have more information about the memory utilization than the GC does (or at least, before it realizes it) and, since the amount of memory reclaimed will be significant, it makes sense to suggest that it runs.

Leave a Comment