清理finalize()或finally()中的代码? [英] Clean up code in finalize() or finally()?

查看:68
本文介绍了清理finalize()或finally()中的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一般的看法,清理资源是在 finally 块中完成的,最近我发现
我在一个类中找到了这个特定的代码片段它覆盖了 Object class' finalize() 方法。

I had the general view that clean up of resources is done in the finally block,
recently I found this particular code snippet in a class and it was overriding the Object class' finalize() method.

protected void finalize() {  
    try {
        In.close(); 
        Out.close();
        socket.close();
    }
    catch (Exception e) {
        //logger code here
    }
}

这是个好主意吗? 最终确定()超过最终的优缺点是什么?

Is this a good idea? What are the pros and cons of finalize() over finally?

推荐答案

finally 块只是一个代码块,总是在尝试后执行阻止,即使有异常。即它是本地的范围

The finally block is just a block of code that always executes after a try block, even if there is an exception. i.e. it is local in scope

finalize()方法是一种清理整个对象的方法垃圾收集。

The finalize() method is an approach for cleaning up the whole object when it is garbage collected.

finalize()的Java文档

finally 解决了代码块中清理资源的问题,无论是否出现异常情况...
finalize()是一种清理资源的方法一旦垃圾收集器确定没有更多对该对象的引用,就不再使用您的对象。

finally solves the problem of cleaning up resources in a block of code regardless of whether an exceptional condition occurs... finalize() is a way to clean up resources when your object is no longer being used, once the Garbage Collecter determines there are no more references to that object.

简而言之,要回答您的问题,例如,如果你要关闭的套接字是一个对象的成员,你应该在 finalize()方法中关闭它们(虽然这是次优的,例如,因为不能保证当GC实际执行动作时)

In short, to answer your question, for example, if the sockets you are closing are members of an object you should close them in the finalize() method, (although that's sub-optimal, and just for example, because there is no guarantee when the GC will actually perform the action)

如果但是你在方法中打开套接字,并在方法结束时完成它,你应该释放 finally 块中的资源。

If however you're opening the socket in a method, and are done with it when the method ends you should free the resources in the finally block.

这篇关于清理finalize()或finally()中的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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