Java Tip: Call the Java Garbage Collector when needed

For long running Java code, which makes heavy use of dynamic memory, you may end up with out-of-memory errors due to a memory shortage of the heap space.

The following code may be added to regularly test the free Java heap space. If the heap space is used more then 90 percent, then the Java garbage collector is explicitly called.

 public void runGC() {
 Runtime runtim e = Runtime.getRuntime();
 long memoryMax = runtime.maxMemory();
 long memoryUsed = runtime.totalMemory() - runtime.freeMemory();
 double memoryUsedPercent = (memoryUsed * 100.0) / memoryMax;

 if (memoryUsedPercent > 90.0)
    System.gc();
 }

Please note that the „System.gc()“ call is blocking the calling thread until the garbage collector has completed. Therefore, this code should be executed in a separate thread.