替换Java中的finalize() [英] Replacing finalize() in Java

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

问题描述

Object.finalize()在Java 9中已弃用,我想我理解原因,但是在查看如何替换它时遇到了麻烦.

Object.finalize() is deprecated in Java 9, and I think I understand the reasons why, but I'm having trouble seeing how to replace it.

我有一个名为Configuration的实用程序类,该实用程序类实际上具有一个实例,该实例拥有应用程序中的所有内容,并且在应用程序运行期间一直存在.它提供的一项服务是日志记录:在首次请求记录消息时,会创建一个记录器(由于各种传统原因,它是我自己的记录器,而不是标准的记录器),并且在Configuration对象的字段中保留了一个引用,并且在终止应用程序时,无论是正常还是异常,我都希望释放记录器所拥有的任何资源(这是一个黑匣子,因为我的库用户可以提供自己的实现).

I have a utility class called Configuration which essentially has a single instance that owns everything in the application and lasts for the duration of the application. One of the services it provides is logging: on first request to log a message, a logger is created (for various legacy reasons it's my own Logger rather than a standard one), with a reference held in a field of the Configuration object, and on application termination, whether normal or abnormal, I want to release any resources held by the logger (which is a black box since users of my library can supply their own implementation).

当前,这是通过调用logger.close()Configuration.finalize()方法实现的.

Currently this is achieved with a Configuration.finalize() method that calls logger.close().

我应该怎么做?

推荐答案

Java 9引入了

Java 9 introduces the Cleaner and Cleanable utility classes which take care of wiring up phantom references to a queue and a cleaning thread draining that queue.

尽管这使您可以分离出拥有对象死亡后将执行事后清理的见证,但有关GC触发的资源管理的所有警告仍然适用,即,仍然更可取的是依赖AutoClosable和try-with-resources块用于管理资源的生命周期,而不是在垃圾收集器上.

While this lets you separate out the witness that will perform a post-mortem cleanup after the owning object has died, all the caveats about GC-triggered resource management still apply, i.e. it is still preferable to rely on AutoClosable and try-with-resources blocks to manage the lifecycle of resources, not on the garbage collector.

这篇关于替换Java中的finalize()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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