组合中的最终结果不确定

时间:2016-06-28 12:33:02

标签: java garbage-collection composition garbage finalize

为什么以下程序的输出在课程的finalize()之前运行Classmate的最终确定? Classmate使用Course对象类,所以它的finalize()应该在Course的finalize()之后运行?但输出显示相反.WHY?

class Classmate{

    Course mca;
    Classmate(){
        System.out.println("Student const. `enter code here`called");
        mca = new Course();
        mca.getCourse();
    }

    @Override
    protected void finalize()  {System.out.println("good bye Student"); 

    }
}
class Course{
    Course(){
        System.out.println("Course const. called"); 
    }

    void getCourse(){
        System.out.println("your ccourse is MCA");
    }

    @Override
    protected void finalize() throws Throwable {
        // TODO Auto-generated method stub
    System.out.println("goodbye course");
    }
}



public class Composition {

public static void main(String[] args) {

    Classmate ram = new Classmate();
    ram=null;
    System.gc();
    for(int i=0;i<5;i++)
        System.out.println("i is "+i);
}
}

输出:

Student const. called

Course const. called

your ccourse is MCA

good bye Student

i is 0

goodbye course

i is 1

i is 2

i is 3

i is 4

1 个答案:

答案 0 :(得分:0)

这样做可以教你(以及任何其他Java程序员)一课。这一课是:不要假设何时调用(或更好如果)finalize。

说真的:你可以看看这个伟大的question,并会发现最终确定的调用与垃圾收集器的操作绑定。事情是:你绝对没有控制权或者有洞察力的#34;当垃圾收集器决定收集东西时。大多数情况下,它的活动会产生相同的结果...如果你不对#34;设置进行更改&#34;你正在处理。比如:使用完全相同的JVM设置运行相同的示例。但是一旦你开始关注现实世界&#34;应用......你会一直遇到意想不到的惊喜。

哎呀 - 甚至不能保证finalize被永远调用。所以,你的代码不应该依赖它。因此,完全使用finalize几乎没有理由。

换句话说:如果你真的想了解发生的事情;您将不得不深入研究JVM正在使用的GC的实现;了解GC为什么以及何时定义垃圾;当它开始收集垃圾时。