Java Reference
In-Depth Information
final ReferenceQueue<Object> queue;
final Map<Reference<?>, Resource> refs;
final Thread reaper;
boolean shutdown = false;
public ResourceManager() {
queue = new ReferenceQueue<Object>();
refs = new HashMap<Reference<?>, Resource>();
reaper = new ReaperThread();
reaper.start();
// ... initialize resources ...
}
public synchronized void shutdown() {
if (!shutdown) {
shutdown = true;
reaper.interrupt();
}
}
public synchronized Resource getResource(Object key) {
if (shutdown)
throw new IllegalStateException();
Resource res = new ResourceImpl(key);
Reference<?> ref =
new PhantomReference<Object>(key, queue);
refs.put(ref, res);
return res;
}
}
The key object can be an arbitrary objectthis gives great flexibility to the
users of the resource, compared to having the resource manager assign
a key. When getresource is invoked, a new ResourceImpl object is cre-
ated, passing in the supplied key. A phantom reference is then created,
with the key as the referent, and using the resource manager's refer-
 
Search WWH ::




Custom Search