1. 设置JVM属性: -Xms64m -Xmx256m 最小64M 最大使用256M.
2. 运行如下代码:
int mb = 1024*1024;
//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();
System.out.println("##### Heap utilization statistics [MB] #####");
// use memory
List testList = new ArrayList();
for(int i =0; i<5000;i++){
Thread.sleep(1000);
for(int i1 =0; i1<5000; i1++){
testList.add(new String[1000]);
}
System.out.println("Used Memory:"
+ (runtime.totalMemory() - runtime.freeMemory()) / mb+"M");
}
System.out.println("Free Memory:" + runtime.freeMemory() / mb+"M");
System.out.println("Total Memory:" + runtime.totalMemory() / mb+"M");
System.out.println("Max Memory:" + runtime.maxMemory() / mb+"M");
}
}
##### Heap utilization statistics [MB] #####
Used Memory:19M
Used Memory:38M
Used Memory:57M
Used Memory:77M
Used Memory:96M
Used Memory:115M
Used Memory:134M
Used Memory:154M
Used Memory:173M
Used Memory:192M
Used Memory:211M
Used Memory:230M
Used Memory:249M
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at prepare.NewClass.main(NewClass.java:32)
Java Result: 1
成功生成(总时间:15 秒)
总结:runtime.totalMemory() 获取Heap大小,runtime.freeMemory() 剩余Heap大小。