System.gc() is evil

I was going through some articles the other day and I came across a few things about System.gc which I would definitely like to share with everybody here.  There is no disagreement on the fact that the exact semantics of how the call works depend upon the implementation of the JVM but keeping in mind that most of the new JVMs implement generational garbage collectors.  System.gc() call would force the system to do a full sweep.  Yes the time of the event would be determined by the JVM on its own discretion but full sweeps are extremely more expensive as compared to regular gc cycles.

If you come across a code with a lot of gc calls rather than going and fixing each one of them, another option could be using XX:+DisableExplicitGC flag which would automatically turns a System.gc() off.

Also -Xloggc could be useful in a lot of such situations, it does the same thing as -verbose:gc but logs to a file instead of spewing to the command-line window.

About Khurram

“If I had only one hour to save the world, I would spend fifty-five minutes defining the problem, and only five minutes finding the solution.” ― Albert Einstein
This entry was posted in Java. Bookmark the permalink.

Leave a comment