In Java9, finalizers have been deprecated and new concept of cleaners have been introduced. What was the specific reason for it? Is there any particular scenario or reason where cleaners should be preferred over finalizer(given that none of them are recommended).?
Cleanup functions, like finalizers, are run when an object is found to be unreachable from any class or thread. Unlike a finalizer, a cleanup function holds the state needed for cleanup separately from the object because we want the object to be reclaimed as soon as it is unreachable.
Deprecated. The finalization mechanism is inherently problematic. Finalization can lead to performance issues, deadlocks, and hangs.
Cleaner manages a set of object references and corresponding cleaning actions. Cleaning actions are registered to run after the cleaner is notified that the object has become phantom reachable. The cleaner uses PhantomReference and ReferenceQueue to be notified when the reachability changes.
Alternatives for finalize()Cleaner Class When finalize() method was deprecated in Java 9, a new class Cleaner was added to garbage collection management. When any object becomes eligible for garbage collection, the object of the Cleaner class gets notified automatically and releases the resources of that class.
The Deprecation of Finalizer in registers state the reason for the decision :-
Finalizers are inherently problematic and their use can lead to performance issues, deadlocks, hangs, and other problematic behavior.
Furthermore, the timing of finalization is unpredictable with no guarantee that a finalizer will be called. Classes whose instances hold non-heap resources should provide a method to enable explicit release of those resources, and they should also implement
java.lang.AutoCloseable
if appropriate.
The proposed solution as an alternative to using the Finalizers were the introduced Cleaners which would provide easy registration and cancellation of cleanup functions for objects.
The
Cleaner
andPhantomReference
provide more flexible and efficient ways to release resources when an object becomes unreachable.
Applications create a cleanup service for their own use and the service terminates when it is no longer in use.
Use: Once an object has become Phantom reachable the cleanup actions performed on the same are registered and managed by a Cleaner. Registering an object reference and corresponding cleaning action returns a Cleanable
. The most efficient use is to explicitly invoke the clean
method when the object is closed or no longer needed.
Note: Prior to Java9, a similar implementation of a Cleaner has been residing under sun.misc
package as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With