一提起如何解决内存溢出问题,动辄使用复杂的监控软件,比如Jprofile等,其实我们可以通过Runtime来获得当前Heap大小,使用Heap大小。测试如下:

  1.  设置JVM属性: -Xms64m -Xmx256m 最小64M 最大使用256M.
  2.  运行如下代码:
通过Runtime获取当前JVM使用的Heap大小 _职场public static void main(String [] args) throws Exception {
通过Runtime获取当前JVM使用的Heap大小 _休闲_03  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03         
int mb = 1024*1024;  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03        
//Getting the runtime reference from system  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03
         Runtime runtime = Runtime.getRuntime();  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03   
通过Runtime获取当前JVM使用的Heap大小 _休闲_03        System.out.println(
"##### Heap utilization statistics [MB] #####");  
通过Runtime获取当前JVM使用的Heap大小 _休闲_03       
// use memory
通过Runtime获取当前JVM使用的Heap大小 _休闲_03
        List testList = new ArrayList();
通过Runtime获取当前JVM使用的Heap大小 _休闲_12        
for(int i =0; i<5000;i++){
通过Runtime获取当前JVM使用的Heap大小 _休闲_03            Thread.sleep(
1000);
通过Runtime获取当前JVM使用的Heap大小 _休闲_15        
for(int i1 =0; i1<5000; i1++){
通过Runtime获取当前JVM使用的Heap大小 _休闲_03        testList.add(
new String[1000]);
通过Runtime获取当前JVM使用的Heap大小 _职场_18        }

通过Runtime获取当前JVM使用的Heap大小 _休闲_03        System.out.println(
"Used Memory:"
通过Runtime获取当前JVM使用的Heap大小 _休闲_03             
+ (runtime.totalMemory() - runtime.freeMemory()) / mb+"M");
通过Runtime获取当前JVM使用的Heap大小 _职场_18        }

通过Runtime获取当前JVM使用的Heap大小 _休闲_03         System.out.println(
"Free Memory:"   + runtime.freeMemory() / mb+"M");
通过Runtime获取当前JVM使用的Heap大小 _休闲_03         System.out.println(
"Total Memory:" + runtime.totalMemory() / mb+"M");
通过Runtime获取当前JVM使用的Heap大小 _休闲_03         System.out.println(
"Max Memory:" + runtime.maxMemory() / mb+"M");
通过Runtime获取当前JVM使用的Heap大小 _休闲_03
通过Runtime获取当前JVM使用的Heap大小 _休闲_26     }

通过Runtime获取当前JVM使用的Heap大小 _休闲_27
通过Runtime获取当前JVM使用的Heap大小 _休闲_27
通过Runtime获取当前JVM使用的Heap大小 _休闲_27}
运行结果如下:
##### 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大小。