运行时freeMemory没有减少,因为我使用更多的内存

时间:2015-04-13 10:32:40

标签: java memory-leaks

我的程序中存在内存泄漏,可能是在我使用JNA调用某些本机函数时。当我不确定时,我决定测试一个导致它的功能。我创建了这个测试:

public class MemoryLeakCheck {
  public static final Runtime runtime = Runtime.getRuntime();
  public static final double mb = 1024*1024;
  public static void main(String[] args) throws Exception {

    //Remember the starting memory for the final comparison
    double usedMemoryStart = getMBUsed();
    System.out.println("Starting with "+String.format("%4.1f", usedMemoryStart));

    //This will be updated to keep track of changes during test
    double lastMemory = usedMemoryStart;

    //Memory change threshold - once the change is greater than this, info will appear in console
    final double threshold = 10;

    while(win.isValid()) {
      //Run the tested operation
        //something here
      //Do not kill the CPU
      Thread.sleep(200);
      //Calculate memory changes
      double mbnew = getMBUsed();
      double diff = mbnew-lastMemory;

      if(diff>=threshold || diff<=-threshold) {
        System.out.println((diff>0?"+":"-")+" "+String.format("%3.3f", diff*(diff>0?01.0D:-1.0D)));
        System.out.println("            = "+String.format("%4.1f", mbnew));
        //Update lastMemory to keep track of the next change
        lastMemory = mbnew;
      }
    }
    //Final change sum
    double mbnew = getMBUsed();
    double diff = mbnew-usedMemoryStart;
    System.out.println("Overall diff: "+String.format("%4.1f", diff));
  }
  /** Will return used memory in MBytes as double. Calculates from difference
   *  between total and free memory.
   * 
   * @return used memory in MBytes.
   */
  public static final double getMBUsed() {
    return (runtime.totalMemory() - runtime.freeMemory())/mb;
  }
}

我开始循环,去煮咖啡。当我回来时,根据任务管理器,相应的java.exe实例使用500MB RAM。但该计划的输出看起来像这样:

Starting with 31,1
- 22,945
            =  8,1
+ 10,754
            = 18,9
+ 10,254
            = 29,2
- 21,284
            =  7,9


  ... repeats a lot ...


+ 10,587
            = 52,2
- 10,579
            = 41,6
+ 10,587
            = 52,2
- 10,579
            = 41,6
Overall diff: 15,9
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time: 2:46.265s
Finished at: Mon Apr 13 12:20:56 CEST 2015
Final Memory: 6M/106M
------------------------------------------------------------------------

如您所见,我的结果和maven输出都不包含正确的值。我很惊讶。这个内存泄漏是否是由我的程序引起的?

0 个答案:

没有答案