研究垃圾回收机制,计算对象创建占用的内存

来源:互联网 发布:淘宝商家放单群 编辑:程序博客网 时间:2024/06/02 10:20


package tigers;

public class Tiger14 {

 public static void main(String[] args) {
  int[] timesArray = {10, 100, 1000, 10000};
  execute("java.lang.StringBuffer", timesArray);
  execute("java.lang.String", timesArray);
  execute("java.lang.Object", timesArray);
 } 
 private static void execute(String className, int[] timesArray) {
  try {
   System.out.println("<+>>>>>> Test: [" + className + "]");
   for (int i : timesArray) {
    long used = usedMemory(className, i);
    System.out.println(used + "(" + i + " times)");
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 private static long usedMemory(String className, int times) throws Exception{
  Class c = Class.forName(className);
  int size = times;
  Object[] obs = new Object[times];
//  runGC();
  rt.gc();
  long start = rt.freeMemory();
  for (int i = 0; i < size; i++) {
   obs[i] = c.newInstance();
  }
//  runGC();
  rt.gc();
  long end = rt.freeMemory();
  return (start - end) / size;
 }
 private static Runtime rt = Runtime.getRuntime();


 private static void runGC() throws Exception{ //试图强制运行垃圾回收。
  long past = Long.MAX_VALUE, now = rt.freeMemory();
  for (int i = 0; (past > now) && (i < 500); i++) { //只有当垃圾回收确实执行以后,现在剩余的内存才会大于过去剩余的内存,for循环才会终止。
   rt.runFinalization(); //强制调用对象的finalize()方法,为垃圾回收作准备。
   rt.gc(); //试图激活垃圾回收线程。

   Thread.yield(); //延迟当前线程,使垃圾回收线程得到执行机会。
   past = now;
   now = rt.freeMemory(); //更新当前内存使用状态
  }
 }
}

使用Runtime.gc()方法实现垃圾回收:

<+>>>>>> Test: [java.lang.StringBuffer]
112(10 times)
64(100 times)
64(1000 times)
63(10000 times)
<+>>>>>> Test: [java.lang.String]
184(10 times)
43(100 times)
40(1000 times)
35(10000 times)
<+>>>>>> Test: [java.lang.Object]
31(10 times)
14(100 times)
8(1000 times)
6(10000 times)
使用自定义的runGC()方法实现垃圾回收:

<+>>>>>> Test: [java.lang.StringBuffer]
-924(10 times)
61(100 times)
64(1000 times)
63(10000 times)
<+>>>>>> Test: [java.lang.String]
200(10 times)
38(100 times)
40(1000 times)
35(10000 times)
<+>>>>>> Test: [java.lang.Object]
47(10 times)
11(100 times)
6(1000 times)
8(10000 times)

原创粉丝点击