问题描述
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 的实用程序类,它本质上只有一个实例,它拥有应用程序中的所有内容并在应用程序期间持续存在.它提供的服务之一是记录:在第一次请求记录消息时,会创建一个记录器(由于各种遗留原因,它是我自己的记录器而不是标准记录器),并在配置对象的字段中保存一个引用,并且在应用程序终止时,无论是正常还是异常,我都想释放记录器持有的任何资源(这是一个黑匣子,因为我的库的用户可以提供他们自己的实现).
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 引入了 Cleaner 和 Cleanable 实用程序类,它们负责将幻像引用连接到队列和清空该队列的清理线程.
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!