Java Reference
In-Depth Information
It is straightforward to implement a class that will cause a set of finalizer-like methods
to be invoked in a specified order for a set of objects when all the objects become un-
reachable. Defining such a class is left as an exercise for the reader.
It is guaranteed that the thread that invokes the finalizer will not be holding any user-visible
synchronization locks when the finalizer is invoked.
If an uncaught exception is thrown during the finalization, the exception is ignored and fi-
nalization of that object terminates.
The completion of an object's constructor happens-before (§
17.4.5
) the execution of its
fi-
nalize
method (in the formal sense of happens-before).
The
finalize
method declared in class
Object
takes no action. The fact that class
Object
declares
a
finalize
method means that the
finalize
method for any class can always invoke the
finalize
method for its superclass. This should always be done, unless it is the programmer's intent
to nullify the actions of the finalizer in the superclass. (Unlike constructors, finalizers do
not automatically invoke the finalizer for the superclass; such an invocation must be coded
explicitly.)
For efficiency, an implementation may keep track of classes that do not override the
finalize
method of class
Object
, or override it in a trivial way.
For example:
protected void finalize() throws Throwable {
super.finalize();
}
We encourage implementations to treat such objects as having a finalizer that is not
A finalizer may be invoked explicitly, just like any other method.
The package
java.lang.ref
describes weak references, which interact with garbage collection
and finalization. As with any API that has special interactions with the Java programming
language, implementors must be cognizant of any requirements imposed by the
java.lang.ref
API. This specification does not discuss weak references in any way. Readers are referred
to the API documentation for details.