szhswl
          宋針還的個人空間

          一個測試程序來估算1M內存能夠緩存多少個對象,代碼如下:

           1 public void testSpike(){
           2  print("最大的內存為:" Runtime.getRuntime().maxMemory()/1024);
           3  print("總的內存為:" Runtime.getRuntime().totalMemory()/1024);
           4  print("==================================");
           5  long currMemory=Runtime.getRuntime().freeMemory();
           6  print("目前可用的內存為:" currMemory/1024);
           7  print("==================================");
           8  Map cache=new HashMap();
           9  for (int i = 0; i < 500000; i ) {
          10   MockBean bean=new MockBean();
          11   bean.setId(i);
          12   bean.setName("jerry" i);
          13   bean.setValue(i "jerry");
          14   cache.put(String.valueOf(i), bean);
          15   long tempMemory=Runtime.getRuntime().freeMemory();
          16   if((currMemory-tempMemory)/1024==1024){
          17    print("此時可用的內存為:" tempMemory/1024);
          18    print("此時緩存了:" i "個對象");
          19    break;
          20   }
          21  }
          22  print("==================================");
          23  cache.clear();
          24  long tempMemory=Runtime.getRuntime().freeMemory();
          25  print("目前可用的內存為:" tempMemory/1024);
          26  print("消耗的內存為:" (currMemory-tempMemory)/1024);
          27  print("==================================");
          28  Runtime.getRuntime().gc();
          29  tempMemory=Runtime.getRuntime().freeMemory();
          30  print("目前可用的內存為:" tempMemory/1024);
          31  print("消耗的內存為:" (currMemory-tempMemory)/1024);
          32 }
          33 
          34 private void print(String msg){
          35  System.out.println(msg);
          36 }
          37 


            結果大概是1M內存可緩存大概4479個對象,同時可以看到,在cache.clear后內存并沒有變化,因為gc是沒那么及時的,這個時候顯式的調用gc則會發現可用的內存量甚至比最初都多。

            當然,這里只是個簡單的測試,這里測試的也只是緩存一個非常簡單的bean對象,緩存的對象消耗的內存大小還需要根據這個對象中具體的內容而定,比如當緩存的是blob類型的字段的時候,可想而知,這個時候消耗的內存量絕對是不同的。

            這里只是建議大家在對系統性能做優化時最好根據需要緩存的內容做一個估算,設置好應用所需要的jvm的內存值,以便充分利用服務器的硬件資源。



          ---------------------------------------------------------------------------------------------------------------------------------
          說人之短,乃護己之短。夸己之長,乃忌人之長。皆由存心不厚,識量太狹耳。能去此弊,可以進德,可以遠怨。
          http://www.aygfsteel.com/szhswl
          ------------------------------------------------------------------------------------------------------ ----------------- ---------
          posted on 2007-12-10 21:04 宋針還 閱讀(331) 評論(0)  編輯  收藏 所屬分類: JAVA
          主站蜘蛛池模板: 麻阳| 红河县| 高碑店市| 安庆市| 抚宁县| 桐乡市| 高雄市| 和顺县| 旬阳县| 萨迦县| 若羌县| 洛隆县| 民丰县| 宣威市| 丘北县| 沐川县| 建始县| 沧州市| 额济纳旗| 南平市| 呼玛县| 枣庄市| 吴堡县| 长垣县| 城固县| 沾化县| 吴旗县| 海门市| 黔江区| 永登县| 柏乡县| 武陟县| 滨州市| 九寨沟县| 汉沽区| 谷城县| 海口市| 台山市| 平顶山市| 四川省| 荣昌县|