在构造函数抛出异常后可以调用finalize吗? [英] Can finalize be called after a constructor throws an exception?

查看:111
本文介绍了在构造函数抛出异常后可以调用finalize吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有关于是否使用 finalize()清除对象的详细信息,如果该对象的构造函数是异常。

Are there any details on whether or not an object is cleaned up using finalize() if that object's constructor thew an exception.

当调用这个方法时,出了名的错误。根据手册:

When this method is called is notoriously ill defined. According to the manual:


Java编程语言不保证
调用任何给定对象的finalize方法。但是,保证
,调用finalize的线程在调用finalize时不会持有任何
用户可见的同步锁。如果finalize方法抛出
未捕获异常,则忽略
异常并终止该对象的终止。

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

http:// docs.oracle.com/javase/7/docs/api/java/lang/Object.html#finalize%28%29

我没有能够以这种方式触发finalize方法。有没有人知道它是不是被调用了,或者在某些情况下是在构造函数初始化对象后调用的(这是一个异常)。

I've not been able to trigger the finalize method in this way. Does anyone know if it is garunteed NOT to be called or if it is in some cases called after the constructor failed to initialize the object (thew an exception).

我问这是因为我有一个不能清理两次的物体。我试图了解在抛出异常之前清理是否安全,或者我是否必须为 finalize()留下标记以有效地跳过并且什么也不做。

I ask this because I have an object which must not be cleaned up twice. I'm trying to understand if it is safe to clean up before throwing the exception or if I must leave a marker for finalize() to effectively skip and do nothing.

推荐答案

我的测试显示它可以

public class Test1 {

    Test1() {
        throw new RuntimeException();
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalized");
    }

    public static void main(String[] args) throws Exception {
        try {
            new Test1();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        System.gc();
        Thread.sleep(1000);
    }
}

打印

java.lang.RuntimeException
    at test.Test1.<init>(Test1.java:13)
    at test.Test1.main(Test1.java:24)
finalized

它位于Java HostSpot Client VM 1.7.0_03上

it is on Java HostSpot Client VM 1.7.0_03

这篇关于在构造函数抛出异常后可以调用finalize吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆