Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don’t know what sort of garbage collector you are running under. There are certainly some that do not “stop the world” as you assert, but some JVMs aren’t that smart or for various reasons (perhaps they are on a phone?) don’t do it. You don’t know what it’s going to do.

Also, it’s not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of “you don’t know what it will do,” “you don’t know if it will even help,” and “you shouldn’t need to call it anyway” are why people are so forceful in saying that generally you shouldn’t call it. I think it’s a case of “if you need to ask whether you should be using this, you shouldn’t”

EDIT to address a few concerns from the other thread:

After reading the thread you linked, there’s a few more things I’d like to point out.
First, someone suggested that calling gc() may return memory to the system. That’s certainly not necessarily true – the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn’t necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it’s possible that System.gc() does nothing, view
JDK bug 6668279
and in particular that there’s a -XX:DisableExplicitGC VM option:

By default calls to System.gc() are enabled (-XX:-DisableExplicitGC). Use -XX:+DisableExplicitGC to disable calls to System.gc(). Note that the JVM still performs garbage collection when necessary.

Leave a Comment