In Java9, finalizers have been deprecated, instead cleaners have been introduced. What is the difference between the two?

Chota Bheem :

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

Naman :

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 and PhantomReference 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=438002&siteId=1