After answering a question about how to force-free objects in Java (the guy was clearing a 1.5GB HashMap) with System.gc()
, I was told it’s bad practice to call System.gc()
manually, but the comments were not entirely convincing. In addition, no one seemed to dare to upvote, nor downvote my answer.
I was told there that it’s bad practice, but then I was also told that garbage collector runs don’t systematically stop the world anymore, and that it could also effectively be used by the JVM only as a hint, so I’m kind of at loss.
I do understand that the JVM usually knows better than you when it needs to reclaim memory. I also understand that worrying about a few kilobytes of data is silly. I also understand that even megabytes of data isn’t what it was a few years back. But still, 1.5 gigabytes? And you know there’s like 1.5 GB of data hanging around in memory; it’s not like it’s a shot in the dark. Is System.gc()
systematically bad, or is there some point at which it becomes okay?
So the question is actually double:
- Why is or isn’t it bad practice to call
System.gc()
? Is it really merely a hint to the JVM under certain implementations, or is it always a full collection cycle? Are there really garbage collector implementations that can do their work without stopping the world? Please shed some light over the various assertions people have made in the comments to my answer. - Where’s the threshold? Is it never a good idea to call
System.gc()
, or are there times when it’s acceptable? If so, what are those times?