![](/img/trans.png)
[英]Sub-class not able to access the protected method of super-class when the reference is of type super-class
[英]behavior of finalize method in sub-class and super-class
我有以下代码。
class SuperClass
{
public void finalize() throws Throwable
{
System.out.println("finalize() in SuperClass...");
}
}
public class FinalizableObject extends SuperClass
{
public static void main(String[] args) throws Exception
{
FinalizableObject obj = new FinalizableObject();
Thread.sleep(1000);
obj = null;
System.gc();
}
public void finalize() throws Throwable
{
super.finalize();
System.out.println("finalize() in FinalizableObject...");
}
}
我得到所有4种可能的输出
1. finalize not called for sub/super class.
2. finalize called for only sub class.
3. finalize called for only super class.
4. finalize called for both super and sub class.
...在程序的不同运行中。 为什么会这样呢?
我的问题不是GC应该在System.gc()调用上运行。 当子类finalize()被调用时,为什么超类finalize不被调用,即使该调用是显式的。
在垃圾回收器回收该对象之前调用finalize(),这是任何对象执行清除活动的最后机会,即释放所有持有的系统资源,如果打开则关闭连接等。
Java中的finalize方法的主要问题是JLS不能保证它会被垃圾收集器调用,或者不能确切地被调用,例如,某个对象在有资格进行垃圾收集之后且在其finalize()方法获取之前可能无限期等待叫。 同样,即使finalize被调用后,也无法保证将立即收集它。
由于上述原因,使用finalize方法释放关键资源或在finalize内部执行任何时间紧迫的活动都是没有意义的。 它可能在一个JVM中进行开发,但在其他JVM中不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.