Replacing finalize () in Java

Object.finalize() deprecated on Java 9, and I think I understand the reasons, but I am having problems with how to replace it.

I have a utility class called Configuration, which essentially has one instance that owns everything in the application and lasts for the duration of the application. One of the services it provides is registration: the first request for registering a message creates a log (for various well-established reasons, its own Logger, and not the standard one), with a link stored in the field of the Configuration object, and when the application terminates, normal or abnormal, I want to free up any resources stored in the log (this is a black box, as users of my library can provide their own implementation).

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

What should I do instead?

+8
source share
4 answers

Phantom links are a common replacement finalize(). Many classes from the Java runtime already use them.

Using phantom links is a little time consuming, you must maintain your own list of links and the processing flow after death. On the other hand, you are in full control of the situation.

Here is a simple example of setting up phantom links.

This article explains and compares the implementation of references to finalize() and Phantom in Java.

+6
source

Java 9 Cleaner Cleanable, , .

, -, , GC, - , AutoClosable try-with-resources , .

+5

Thread Runtime:

Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    // cleanup code
}));

, VM , finalize

+3

IMHO this is not the responsibility of your application to tell the registrar to clear your mess. The registrar itself can and should do this as (unlike IO streams or database connections), it must live a long time.

But you already provide logger.close()... OK, then I would suggest the following:

  • Make sure that it closeis idempotent, i.e. closing the registrar a second time is non-op.
  • Use both Runtime#addShutdownHook, and PhantomReference, and let them invoke logger.close()so that it is invoked both upon completion of the JVM and upon receipt of your GC application.
+2
source

Source: https://habr.com/ru/post/1690585/


All Articles