不对。
终结函数是当无用的对象被垃圾回收的时候由GC调用的方法,做一些自定义的任务,并不进行什么存储空间的释放。它本身没有做到时间关键的可靠性,也无法自动跟踪到父类的终结函数,必须显示维护终结链。
对于使用finalize()函数的建议:能够不用就绝对不用。
终结函数是当无用的对象被垃圾回收的时候由GC调用的方法,做一些自定义的任务,并不进行什么存储空间的释放。它本身没有做到时间关键的可靠性,也无法自动跟踪到父类的终结函数,必须显示维护终结链。
对于使用finalize()函数的建议:能够不用就绝对不用。
import java.util.Arrays;
public class GcAndFinalize extends Thread { public static void main(String[] args) {
for (int i = 0; i < 1000 ;i++) {
TA ta = new TA(i);
}
// ta = null;
// System.gc(); }
}class TA {
int i;
char[] mem = new char[999];
public TA(int in) {
i = in;
Arrays.fill(mem,'a');
System.out.println("Object is Creating...." + in);
} protected void finalize() throws Throwable {
super.finalize();
System.out.println("GC is running....Destory object" + i);
}
}
========================================
if ( ! 手头有<Effective Java> ) {
买一本<Effective Java>;
}
参见关于终结函数规则的那一章;
另外,finalize可能永远都不会执行,所以程序的正确性绝对不能依赖它的执行。
2.
Garbage Collector根据“需要”而决定销毁某些对象。并不是程序一退出马上就会被销毁。
3.
你可以调用垃圾收集器“System.gc();”,但调用的含义是“你要求系统来回收”,系统收到了这个请求,但系统是否真正的去回收,会根据线程繁忙程度来判断。如果线程正闲置,会响应你的请求。4.按上面的分析,把只要让句柄不在引用对象,对象会被立刻回收,当你调用System.gc()的时候。6.书写事例代码如下:
public class TestGC{
public void finalize(){
System.out.print("the erroe");
}
public static void main(String[] args)
{
TestGC test = new TestGC();
test = new TestGC();
test = null;
System.gc();
System.out.println("Hello World!");
}
}7.程序说明:
test = null,让test失去了对new TestGC()的引用。new TestGC()对象没有任何人在引用。在你申请GC的时候,就被回收了。因为此时系统只运行你一个线程(还有其他后台辅助的),当然有空闲时间,于是立刻回收了你的。程序输出“the erroeHello World!”。8.同理,下面的代码,也会输出回收调用的结果。
public class TestGC{
public void finalize(){
System.out.print("the erroe");
}
public static void main(String[] args)
{
TestGC test = new TestGC();
test = new TestGC();
test = new TestGC(); System.gc();
System.out.println("Hello World!");
}
}