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
          主站蜘蛛池模板: 贵定县| 普格县| 资溪县| 含山县| 会泽县| 霍林郭勒市| 中超| 桂东县| 清原| 宁晋县| 子洲县| 鄂伦春自治旗| 遵义市| 阜新市| 台安县| 呼和浩特市| 赣榆县| 余姚市| 阜平县| 根河市| 尼玛县| 云阳县| 西昌市| 德化县| 武安市| 安康市| 石台县| 密云县| 惠水县| 建湖县| 防城港市| 沐川县| 元江| 石狮市| 冷水江市| 共和县| 景东| 文水县| 额尔古纳市| 汨罗市| 文山县|