I know that garbage collection is automated in Java. But I understood that if you call System.gc()
in your code that the JVM may or may not decide to perform ga
The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc()
. This is the reason of this "may or may not decide to do a GC at that point".
Now, if you look at OpenJDK source code, which is the backbone of Oracle JVM, you will see that a call to System.gc()
does start a GC cycle. If you use another JVM, such as J9, you have to check their documentation to find out the answer. For instance, Azul's JVM has a garbage collector that runs continuously, so a call to System.gc()
won't do anything
Some other answer mention starting a GC in JConsole or VisualVM. Basically, these tools make a remote call to System.gc()
.
Usually, you don't want to start a garbage collection cycle from your code, as it messes up with the semantics of your application. Your application does some business stuff, the JVM takes care of memory management. You should keep those concerns separated (don't make your application do some memory management, focus on business).
However, there are few cases where a call to System.gc()
might be understandable. Consider, for example, microbenchmarks. No-one wants to have a GC cycle to happen in the middle of a microbenchmark. So you may trigger a GC cycle between each measurement to make sure every measurement starts with an empty heap.