Java Reference
In-Depth Information
17.3. Finalization
You won't normally notice when an orphaned object's space is re-
claimed"it just works." But a class can implement a finalize method that
is executed before an object's space is reclaimedsee " Strengths of Refer-
ence and Reachability " on page 455 . Such a finalize method gives you
a chance to use the state contained in the object to reclaim other non-
memory resources. The finalize method is declared in the Object class:
protected void finalize() tHRows Throwable
Is invoked by the garbage collector after it determines that this
object is no longer reachable and its space is to be reclaimed.
This method might clean up any non-memory resources used
by this object. It is invoked at most once per object, even if
execution of this method causes the object to become reach-
able again and later it becomes unreachable again. There is no
guarantee, however, that finalize will be called in any specific
time period; it may never be called at all. This method is de-
clared to throw any exception but if an exception occurs it is ig-
nored by the garbage collector. The virtual machine makes no
guarantees about which thread will execute the finalize meth-
od of any given object, but it does guarantee that the thread
will not hold any user-visible synchronization locks.
You should only rarely need to write a finalize method, and when you do,
you should write it with great care. If your object has become garbage
it is quite possible that other objects to which it refers are also garbage.
As garbage, they may have been finalized before your finalize method is
invoked and may therefore be in an unexpected state.
Garbage collection collects only memory. When you are dealing with non-
memory resources that are not reclaimed by garbage collection, finalizers
look like a neat solution. For example, open files are usually a limited re-
source, so closing them when you can is good behavior. But this usually
cannot wait until the finalize phase of garbage collection. The code that
asks you to perform an operation that opens a file should tell you when
 
Search WWH ::




Custom Search