我为了验证finalize()的效果,写了一个程序,如下:
这个是主程序,调用System.gc(),
程序名:FinalizeTst.java
package tst;/**
 * @file_name FinalizeTst.java
 * @author ([email protected])
 * @date 2007-6-8 下午08:46:42
 * @description 
 * @reviewed_by
 */
public class FinalizeTst  {
/**
 * @method_name main
 * @author [email protected]
 * @date 2007-6-8 下午08:46:44
 * @description 
 * @param args 
 * @reviewed_by
 */
public static void main(String[] args) {
// TODO 自动生成方法存根
Test ft = new Test();
ft.show();
System.gc();
System.out.println("now the i is exist?"+ ft.getI().toString());
}

}另外一个类Test.java如下:程序名:Test.javapackage tst;
class Test {
private  Integer i;

public Test()
{
this.i=5;
}
protected void finalize(){
System.out.println("gabbage collected");
}

protected void show(){
System.out.println("the i is :" +this.i);
}

protected Integer getI() {
return this.i;
}
}程序输出为:
the i is :5
now the i is exist?5
按照我的想法:
应该会输出Test类中方法finalize()的打印内容,因为不是说,如果你调用System.gc()的时候,就会先调用finalize()的阿,为什么没有调用呢?哪位高手给我解答一下!先多谢了!
  

解决方案 »

  1.   

    测试发现,在垃圾回收前要检查是否存在无效对象,如果没有无限对象,则即使调用System.gc()也不会执行垃圾回收。
    public static void main(String[] args) {
    // TODO 自动生成方法存根
    Test ft = new Test();//创建对象被引用,不被认为是垃圾
    ft.show();
    new Test();//创建了对象但是没有被引用,被认为是垃圾
    System.gc();
    System.out.println("now the i is exist?"+ ft.getI().toString());
    }程序输出为:
    the i is :5
    gabbage collected
    now the i is exist?5
      

  2.   

    那就是说内存现在是够用的,你就是强制调用System.gc(),也不会去执行Test类中的finalize(),是这个意思吧 ?
      

  3.   

    不是,你的代码是这样写的:
     public static void main(String[] args) {
    // TODO 自动生成方法存根
    Test ft = new Test();
    ft.show();
    System.gc();-----------------------------------------------------------------------1
    System.out.println("now the i is exist?"+ ft.getI().toString());-------------------2
    }
    在2处你还在用ft,所以在1处不被认为是垃圾!
      

  4.   

    是吗,我试2处不打印,still cant call finalize(),who can give me more detail explantation? My input has been destroyed,so pardon ,please!
      

  5.   

    Test ft = new Test();
    ft.show();
    ft=null;//注意这里要声明为null,这样在gc的时候才会被认为是垃圾
    System.gc();
    //System.out.println("now the i is exist?"+ ft.getI().toString());
    //这里你既然还在调用ft,那系统就认为ft还不是垃圾
      

  6.   

    垃圾回收是JVM调用的。无法知道他会在什么时候调用。一般是内存不够的情况下!
    System.gc()是建议JVM垃圾回收。他听不听你的再说!
      

  7.   


    垃圾回收是JVM调用的。无法知道他会在什么时候调用。一般是内存不够的情况下!
    System.gc()是建议JVM垃圾回收。他听不听你的再说!引用楼上的
      

  8.   

    多谢 redduke102!散分了!测试通过,就是应该把ft=null!
      

  9.   

    垃圾回收应该是JVM自己去处理
    你调用了gc()后并不代表着JVM立刻就去做垃圾回收
    只是告诉JVM有垃圾需要回收
    JVM自己判断在什么时候应该回收(一般是内存不足)