Java Reference
In-Depth Information
ReaperThread is an inner class, and a given reaper thread runs until its
associated resource manager is shut down. It blocks on remove until a
phantom reference associated with a particular key has been enqueued.
The phantom reference is used to get a reference to the Resource object
from the map, and then that entry is removed from the map. The Re-
source object then has release invoked on it to release the resource. Fin-
ally, the phantom reference is cleared so that the key can actually be
reclaimed.
As an alternative to using a separate thread, the getresource method
could instead poll the queue whenever it is called and release any re-
sources whose key has become unreachable. The shutdown method could
then do a final poll, too. The semantics for the resource manager neces-
sarily depend on the actual kind of resource and its usage patterns.
A design that uses reference queues can be more reliable than direct use
of finalizationparticularly with phantom referencesbut remember that
there are no guarantees as to exactly when or in what order a reference
object will be enqueued. There are also no guarantees that by the time
an application terminates, all enqueuable reference objects will have
been enqueued. If you need to guarantee that all resources are released
before the application terminates, you must install the necessary shut-
down hooks (see " Shutdown " on page 672 ) or other application-defined
protocols to ensure this happens.
Exercise 17.3 : Rework the resource implementation class so that it
uses a reference object to keep track of the key instead of using the
hash code.
Exercise 17.4 : Modify the reaper thread so that it stays alive after
shutdown until all the allocated resources can be released.
Exercise 17.5 : Redesign the resource manager to not use a reaper
thread. Be clear on what semantics the resource manager has and on
when resources will be released.
 
Search WWH ::




Custom Search