

In the debugger, I could perform System.gc() and sure enough there would be "plenty" of memory available.not a lot of extra, but enough.Ĭonsequently, The only time my application calls System.gc() is when it is about to enter the segment of code where large buffers necessary for processing the data will be allocated, and a test on the free memory available indicates that I'm not guaranteed to have it. I am currently working on a project involving a memory-limited environment and a relatively large amounts of data-there are a few large pieces of data that push my environment to its limit, and even though I was able to bring memory usage down so that in theory it should work just fine, I would still get heap space errors-the verbose GC options showed me that it was trying to garbage collect, but to no avail. There is a LOT to be said in taking the time to test out the various garbage collection settings, but as was mentioned above it usually not useful to do so. So you may trigger a GC cycle between each measurement to make sure every measurement starts with an empty heap.

No-one wants to have a GC cycle to happen in the middle of a microbenchmark. However, there are few cases where a call to System.gc() might be understandable. You should keep those concerns separated (don't make your application do some memory management, focus on business). Your application does some business stuff, the JVM takes care of memory management. Usually, you don't want to start a garbage collection cycle from your code, as it messes up with the semantics of your application. Basically, these tools make a remote call to System.gc(). Some other answer mention starting a GC in JConsole or VisualVM. For instance, Azul's JVM has a garbage collector that runs continuously, so a call to System.gc() won't do anything

If you use another JVM, such as J9, you have to check their documentation to find out the answer. 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. This is the reason of this "may or may not decide to do a GC at that point". The Java Language Specification does not guarantee that the JVM will start a GC when you call System.gc().
