Java Reference
In-Depth Information
porary files can be marked as "delete on exit," which solves one of the
more common issuessee "
The File Class
"
on page
543
.
)
Reference queuesdiscussed on page
459
provide a better way of per-
forming clean-up actions when an object is it about to be, or has been,
reclaimed.
17.3.1. Resurrecting Objects during
finalize
A
finalize
method can "resurrect" an object by making it referenced
againfor example, by adding it to a static list of objects. Resurrection is
discouraged, but there is nothing the system can do to stop you.
However, the virtual machine invokes
finalize
at most once on any ob-
ject, even if that object becomes unreachable more than once because
a previous
finalize
resurrected it. If resurrecting objects is important to
your design, the object would be resurrected only onceprobably not the
behavior you wanted.
If you think you need to resurrect objects, you should review your
design carefullyyou may uncover a flaw. If your design review convinces
you that you need something like resurrection, the best solution is to
clone the object or create a new object, not to resurrect it. The
final-
ize
method can insert a reference to a new object that will continue the
state of the dying object rather than a reference to the dying object it-
self. Being new, the cloned object's
finalize
method will be invoked in
the future (if needed), enabling it to insert yet another copy of itself in
yet another list, ensuring the survival, if not of itself, at least of its pro-
geny.