Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

garbage collection - Replacing finalize() in Java

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.

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).

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

What should I be doing instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...