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

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

问题描述

我已经阅读了很多关于 finalize() 的 Java 新手问题,发现没有人真正明确表示 finalize() 是一种不可靠的方法,这有点令人困惑清理资源.我看到有人评论说他们用它来清理连接,这真的很可怕,因为接近保证连接关闭的唯一方法是最终实现 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 provide specific scenarios or your experience, simply repeating a Java text book, or finalize's intended use is not enough, as 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 开销.仅在长时间运行的应用中需要腰带和吊带"安全时才使用.

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.Cleanerjava.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天全站免登陆