一提起如何解决内存溢出问题,动辄使用复杂的监控软件,比如Jprofile等,其实我们可以通过Runtime来获得当前Heap大小,使用Heap大小。测试如下:
1. 设置JVM属性: -Xms64m -Xmx256m 最小64M 最大使用256M.
2. 运行如下代码:
public static void main(String [] args) throws Exception {
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");
}
}