新的起点 新的开始

快乐生活 !

通过Runtime获取当前JVM使用的Heap大小

        一提起如何解决内存溢出问题,动辄使用复杂的监控软件,比如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");

     }



}
运行结果如下:
##### 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大小。



posted on 2009-05-20 21:59 advincenting 阅读(1587) 评论(1)  编辑  收藏

评论

# re: 通过Runtime获取当前JVM使用的Heap大小[未登录] 2009-05-21 09:55 kimi

通过java.lang.management中的类,能够获得更详细的信息  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

公告

Locations of visitors to this page

导航

<2009年5月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

常用链接

留言簿(13)

随笔分类(71)

随笔档案(179)

文章档案(13)

新闻分类

IT人的英语学习网站

JAVA站点

优秀个人博客链接

官网学习站点

生活工作站点

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜