Java Reference
In-Depth Information
1. When a finalizable object is no longer reachable, a reference to it is placed on
an internal inalization queue and the object is marked, and considered live for
the purposes of the GC run.
2. One by one, objects on the finalization queue are removed and their final
ize() methods are invoked.
3. After a finalizer is invoked, the object is not freed right away. This is because a
finalizer method could resurrect the object by storing the this reference some‐
where (for example, in a public static field on some class) so that the object
once again has references.
4. Therefore, after finalize() has been called, the garbage collection subsytem
must redetermine that the object is unreachable before it can be garbage
collected.
5. However, even if an object is resurrected, the finalizer method is never invoked
more than once.
6. All of this means that objects with a finalize() will usually survive for (at
least) one extra GC cycle (and if they're long-lived, that means one extra
full GC).
The central problem with finalization is that Java makes no guarantees about when
garbage collection will occur or in what order objects will be collected. Therefore,
the platform can make no guarantees about when (or even whether) a finalizer will
be invoked or in what order finalizers will be invoked.
This means that as an automatic cleanup mechanism for protecting scarce resources
(such as filehandles), this mechanism is broken by design. We cannot guarantee that
finalization will happen fast enough to prevent us from running out of resources.
The only real use case for a finalizer is the case of a class with native methods, hold‐
ing open some non-Java resource. Even here, the block-structured approach of try -
with-resources is preferable, but it can make sense to also declare a public native
finalize() (which would be called by the close() method)—this would release
native resources, including off-heap memory that is not under the control of the
Java garbage collector.
y
y d
Finalization Details
For the few use cases where finalization is appropriate, we include some additional
details and caveats that occur when using the mechanism:
• The JVM can exit without garbage collecting all outstanding objects, so some
finalizers may never be invoked. In this case, resources such as network con‐
nections are closed and reclaimed by the operating system. Note, however, that
if a finalizer that deletes a file does not run, that file will not be deleted by the
operating system.
Search WWH ::




Custom Search