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()
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
