System.runFinalization() 和 System.gc() 的区别(没分就没人回说~~~)
看Thinking in java.pdf里面关于这两个函数。稀里糊涂的;(P210-212)
做了n多测试后终于清楚了许多。;;;;;;
System.runFinalization();//好象是在可用内存不足的时候由系统分配执行清理
System.gc(); //到这里时后强制执行清理工作
如果不对,还请各位指正;
F@0
F@1
F@2 这三个为注释行是否有效(True 为不注释;False为注释掉了)
F@1和F@2是或的关系;
测试代码(书上的):
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 == 47 )
// System.out.println("Created 47");
System.out.print("Created:");
System.out.println(i);
//F@0: if(i >= 1000) f = true;
}
public void finalize() { //开始清理的时候自动调用它.
System.out.println("i" + i + ":" + created + " this=" + this.i);
if( !gcrun ) {
gcrun = true;
System.out.println("Beginning to finalize after " + created + " Chairs have been created");
}
if( i == 47 ) {
System.out.println("Finalizing Chair $47, Setting flag to stop Chair creation");
f = true;
}
finalized++;
if( finalized >= created){
System.out.print("All " + finalized + " finalized");
}
System.out.println("-----end finalized;");
if( i>=10000 ) {
System.out.println("- - - - - - - - - stoped - - - - - =");
f = true;
}
}
}
public class Garbage {
public static void main(String args[]) {
// System.runFinalization(); // 没效果。或许是调用它的时候垃圾不需要清理
while( !Chair.f ) {
new Chair();
new String("-------------------------------------");
//F@1 if( (Chair.created % 2) == 1 ) System.gc();
// System.gc(); // 强迫执行垃圾回收器。
//F@2 System.runFinalization(); // 好象是在可用内存不足的时候由系统分配执行清理
}
System.out.println( "After all Chair have been Created:\n Total Created = " + Chair.created + " Total finalized = " + Chair.finalized);
if( args.length > 0 ) {
if( args[0].equals("gc") || args[0].equals("all") ) {
System.out.println("gc():");
System.gc();
}
if( args[0].equals("finalize") || args[0].equals("all") ) {
System.out.println("runFinalization():");
System.runFinalization();
}
}
System.out.println("bye!");
}
}