你为什么要实现finalize()? [英] Why would you ever implement finalize()?

查看:233
本文介绍了你为什么要实现finalize()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读关于finalize()的很多新手Java问题,并发现有点令人困惑的是,没有人真正说明finalize()是一种不可靠的清理资源的方法。我看到有人评论说他们用它来清理Connections,这真的很可怕,因为接近Connection的一个保证就是最终实现try(catch)。

I've been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize() is an unreliable way to clean up resources. I saw someone comment that they use it to clean up Connections, which is really scary since the only way to come as close to a guarantee that a Connection is closed is to implement try (catch) finally.

我没有接受过CS培训,但是我已经用Java专业编程近十年了,我从未见过有人在生产系统中实现finalize()永远。这仍然不意味着它没有它的用​​途,或者我曾与之合作过的人都做得对。

I was not schooled in CS, but I have been programming in Java professionally for close to a decade now and I have never seen anyone implement finalize() in a production system ever. This still doesn't mean that it doesn't have its uses, or that people I've worked with have been doing it right.

所以我的问题是,什么用例是否用于实现finalize(),该语句无法通过语言中的其他进程或语法更可靠地处理?

So my question is, what use cases are there for implementing finalize() that cannot be handled more reliably via another process or syntax within the language?

请提供具体方案或您的经验,只是重复Java教科书,或最终确定预期用途是不够的,并不是这个问题的意图。

Please provided specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, and is not the intent of this question.

推荐答案

您可以将它用作持有外部资源(套接字,文件等)的对象的后备。实现一个 close()方法和文档,告诉它需要调用它。

You could use it as a backstop for an object holding an external resource (socket, file, etc). Implement a close() method and document that it needs to be called.

实现 finalize()如果检测到它没有完成,则执行 close()处理。也许有一些东西倾倒到stderr,指出你在一个有缺陷的来电者之后正在清理。

Implement finalize() to do the close() processing if you detect it hasn't been done. Maybe with something dumped to stderr to point out that you're cleaning up after a buggy caller.

它在特殊/错误情况下提供额外的安全性。并非每个调用者都会每次都执行正确的 try {} finally {} 。不幸的是,但在大多数环境中都是如此。

It provides extra safety in an exceptional/buggy situation. Not every caller is going to do the correct try {} finally {} stuff every time. Unfortunate, but true in most environments.

我同意这很少需要。正如评论者指出的那样,它带有GC开销。只有在长时间运行的app中需要腰带和吊带安全时才使用。

I agree that it's rarely needed. And as commenters point out, it comes with GC overhead. Only use if you need that "belt and suspenders" safety in a long-running app.

我看到从Java 9开始, Object.finalize() 已弃用!他们指出我们 java .lang.ref.Cleaner java.lang.ref.PhantomReference 作为替代品。

I see that as of Java 9, Object.finalize() is deprecated! They point us to java.lang.ref.Cleaner and java.lang.ref.PhantomReference as alternatives.

这篇关于你为什么要实现finalize()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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