Core Java

Deprecating Java’s Finalizer

JDK-8165641 (“Deprecate Object.finalize”) has been opened to “deprecate Object.finalize()” because “finalizers are inherently problematic and their use can lead to performance issues, deadlocks, hangs, and other problematic behavior” and because “the timing of finalization is unpredictable with no guarantee that a finalizer will be called.” I recently experienced and wrote about some of these nasty consequences of using Object.finalize() in the post Java’s Finalizer is Still There.

In the message RFR 9: 8165641 : Deprecate Object.finalize, Roger Riggs invites review and comment on the changes associated with this issue [150 new lines that include the addition of @Deprecated to java.lang.Object.finalize() and numerous additions of @SuppressWarnings(“deprecation”) annotations on current JDK classes’ implementations of Object.finalize() methods].

The proposed addition of Javadoc @deprecated-associated text for the Object.finalize() method restates descriptive information included in JDK-8165641 and in Roger Riggs’s message. This includes the recommendations to “implement java.lang.AutoCloseable if appropriate” for “classes whose instances hold non-heap resources” and to “provide a method to enable explicit release of those resources.” The descriptive information also states, “The {@link java.lang.ref.Cleaner} and {@link java.lang.ref.PhantomReference} provide more flexible and efficient ways to release resources when an object becomes unreachable.” See JDK-8138696 for more background on JDK 9-introduced java.lang.ref.Cleaner. The deprecation of Object.finalize() includes the enhanced @Deprecated annotation to state since when the method has been deprecated [@Deprecated(since="9")].

Although the proposed deprecation of Object.finalize() won’t remove the ability to use the Java finalizer or reduce any of its potential negative consequences, it will at least provide an even more obvious warning about the risks of using that approach and, as currently documented, provides better potential alternatives to be considered.

Reference: Deprecating Java’s Finalizer from our JCG partner Dustin Marx at the Inspired by Actual Events blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Sam
Sam
7 years ago

I used to like using destructors in C++ because if I have an object where a file is opened then I could close it in a destructor. But using Java, I had to keep track of how many objects were using my file object and then close the file when there were no users left.

Back to top button