Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 661
Michael Kay Avatar asked Dec 11 '17 23:12

Michael Kay


People also ask

What can I use instead of finalize in Java?

If you truly manage a non-memory resource, you should use an explicit cleanup action, i.e. a method like dispose() or close() , to be invoked after use. The straight-forward approach is to let the class implement AutoClosable (or a subtype of it) and use the try-with-resources statement.

Is finalize method deprecated in Java?

The finalize method has been deprecated and will be removed. Subclasses that override finalize in order to perform cleanup should be modified to use alternative cleanup mechanisms and to remove the overriding finalize method. When overriding the finalize method, its implementation must explicitly ensure that super.

Why finalize () method should be avoided in Java?

“This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.” So, in one way we can not guarantee the execution and in another way we the system in danger.

Can we override finalize method in Java?

The finalize() method is a pre-defined method in the Object class and it is protected. The purpose of a finalize() method can be overridden for an object to include the cleanup code or to dispose of the system resources that can be done before the object is garbage collected.


1 Answers

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.

like image 178
the8472 Avatar answered Sep 29 '22 08:09

the8472