对于 长时间使用大量动态内存的Java代码,由于堆空间的内存不足,我们可能最终会遇到内存不足错误。
在下面的程序中,我们可以测试程序使用的空闲Java堆空间。如果堆空间的使用率超过90%,则显式调用垃圾回收器。该System.gc()的调用是阻塞调用线程,直到垃圾收集已完成。因此,可以在单独的线程中执行此代码。
public class GCTest {
   public void runGC() {
      Runtime runtime = Runtime.getRuntime();
      long memoryMax = runtime.maxMemory();
      long memoryUsed = runtime.totalMemory() - runtime.freeMemory();
      double memoryUsedPercent = (memoryUsed * 100.0) / memoryMax;
      System.out.println("memoryUsedPercent: " + memoryUsedPercent);
      if (memoryUsedPercent > 90.0)
         System.gc();
   }
   public static void main(String args[]) {
      GCTest test = new GCTest();
         test.runGC();
   }
}输出结果
memoryUsedPercent: 0.07187129404943532