Replacing finalize() in Java(在 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 的实用程序类,它本质上只有一个实例,它拥有应用程序中的所有内容并在应用程序期间持续存在.它提供的服务之一是记录:在第一次请求记录消息时,会创建一个记录器(由于各种遗留原因,它是我自己的记录器而不是标准记录器),并在配置对象的字段中保存一个引用,并且在应用程序终止时,无论是正常还是异常,我都想释放记录器持有的任何资源(这是一个黑匣子,因为我的库的用户可以提供他们自己的实现).
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中替换 finalize()
基础教程推荐
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
