Java Reference
In-Depth Information
Thread t = new
new Thread ( r );
t . setDaemon ( true
true );
t . start ();
}
All of that is in a private static inner class hidden from the developer using the actual
class, which looks like this:
public
public class
class CleanupExample
CleanupExample {
private
private CleanupFinalizer cf ;
private
private HashMap data = new
new HashMap ();
public
public CleanupExample () {
cf = new
new CleanupFinalizer ( this
this );
}
... methods to put things into the hashmap ...
public
public void
void close () {
data = null
null ;
cf . setClosed ();
}
}
Developers construct this object just as they would any other object. They are told to call the
close() method, which will clean up the native memory—but if they don't, it's OK. The
weak reference still exists behind the scenes, so the CleanupFinalizer class has its own
chance to clean up that memory when the inner class processes the weak reference.
The one tricky part of this example is the need for the pendingRefs set of weak references.
Without that, the weak references themselves will be collected before there is the chance to
put them onto the reference queue.
This example overcomes two limitations of the traditional finalizer: it offers better perform-
ance, because the memory associated with the referent object (the data hashmap in this case)
is released as soon as the referent is collected (rather than doing that in the finalizer()
method). And there is no way for the referent object to be resurrected in the cleanup code,
since it has already been collected.
Still, other objections that apply to the use of finalizers apply to this code as well: you can't
ensure the garbage collector will ever get around to freeing the referent, nor that the referen-
Search WWH ::




Custom Search