在 Java 中替换 finalize()

2023-07-12Java开发问题
22

本文介绍了在 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13