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
          主站蜘蛛池模板: 壶关县| 上栗县| 望谟县| 安顺市| 方正县| 静宁县| 永定县| 丹阳市| 锦屏县| 新泰市| 鄄城县| 杭锦后旗| 靖宇县| 柞水县| 彭州市| 汤阴县| 江华| 义马市| 漾濞| 泗洪县| 蓬溪县| 兴化市| 万宁市| 建昌县| 太湖县| 攀枝花市| 定西市| 孝义市| 多伦县| 霸州市| 抚远县| 余姚市| 龙岩市| 华安县| 新建县| 大名县| 景谷| 弥渡县| 万载县| 宝山区| 林芝县|