日期:2014-05-20 浏览次数:20869 次
package selfimpr.ThinkInJava.gc; public class Chair { static boolean gcrun = false; static boolean f = false; static int created = 0; static int finalized = 0; int i; Chair() { i = ++created; if(created == 35000) System.out.println("Created 35000"); } protected void finalize() { //检测gc的第一次运行,gc第一次运行时调用finalize方法会触发并输出 if(!gcrun) { gcrun = true; System.out.println("Beginning to finalize after " + created + " Chairs have been ced. "); } //监测收集编号i值为35000的Chair对象. if(i==35000) { System.out.println("Finalizing Chair #35000, " + "i" + i + " " + created + "Setting flag to stop Chair creation"); //当i值为35000的Chair的对象被垃圾收集后, 将f设置为true, 结束创建. f = true; } //记录销毁对象的数目 finalized ++; if(finalized >= created-100) System.out.println("All " + finalized + " finalized"); } }
package selfimpr.ThinkInJava.gc; public class Garbage { public static void main(String[] args) { if(args.length == 0) { System.err.println("Usage: \n" + "java Garbage before\n or:\n" + "java Garbage after"); return ; } //1. Chair.f为假时不断的创建Chair和String对象. while(!Chair.f) { new Chair(); new String("To take up space"); } //结束创建活动后, 打印总共被创建了多少Chair对象. //在这个过程中, JVM自动运行的垃圾回收回收了多少个Chair对象. System.out.println("After all Chairs have been created:\n" + "total created = " + Chair.created + ", total finalized = " + Chair.finalized); if(args[0].equals("before")) { System.out.println("gc():"); System.gc(); System.out.println("runFinalization():"); System.runFinalization(); } //这个地方进行了改动, 下面这两行代码是新加的. //这里我做了两次测试 /* * 第一次, 调用一次System.gc(); * 第二次, 调用两次System.gc(); * 然而, 和Think in java的讲法不同, 我调用第一System.gc()的时候, * 程序中没有释放的其他对象的finalize方法并没有被调用. * 而我调用两次System.gc();所有没有被释放的对象的finalize方法都被调用了. * * 因此, 感觉至少在jdk6.0_update_10中, GC的运行是在第二次的时候, * 才调用finalize方法并释放内存的. */ System.gc(); System.gc(); //被改动的代码结束 System.out.println("bye!"); if(args[0].equals("after")) System.runFinalizersOnExit(true); } }