Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News Java Finalization to be Deprecated?

Java Finalization to be Deprecated?

This item in japanese

A recent mail in the OpenJDK mailgroup core-libs-dev has proposed the deprecation of the method Object.finalize().

The deprecation of a method present on Java's Object type, would be a highly unusual step. The finalize() method has been present since Java 1.0, and is widely regarded as a misfeature and a significant piece of legacy cruft in the platform.

An object that overrides finalize() is treated specially by the garbage collector. Usually, an object is immediately destroyed during the collection cycle after the object is no longer in scope. However, finalizable objects are instead moved to a queue, where separate finalization threads will drain the queue and run the finalize() method on each object. Once the finalize() method terminates, the object will at last be ready for garbage collection in the next cycle.

The aim of the mechanism was to provide an equivalent in Java to the C++ RAII pattern, where resources (such as filehandles) are acquired when an object is created and automatically released when the object is destroyed.

However, finalization does not safely implement automatic resource management, as the garbage collector does not run with any time guarantees. This means that there is nothing in the mechanism which ties resource release to the lifetime of the object, and so it is always possible to exhaust resources.

Using finalization is therefore not fit for the main purpose it was originally implemented.

The advice given to developers by Oracle (and Sun) has, for many years, been to avoid finalization in ordinary application code. This deprecation is a first step towards eventual removal, but all it actually does is to introduce a formal compiler warning if the finalization mechanism is used.

The actual removal of the feature does not have any timeline yet, partly because there are some use cases for finalization within the platform that are not tied to management of potentially scarce resources. Consensus has yet to emerge about how to migrate those use cases to alternatives.

Assuming that this deprecation warning does indeed ship as part of Java 9 (as seems likely), then the earliest that removal could occur is Java 10. However, it is unclear that removal would definitely happen in that release, or in any later one.

Rate this Article