Java Reference
In-Depth Information
keyHash = System.identityHashCode(key);
// .. set up the external resource
needsRelease = true;
}
public void use(Object key, Object... args) {
if (System.identityHashCode(key) != keyHash)
throw new IllegalArgumentException("wrong key");
// ... use the resource ...
}
public synchronized void release() {
if (needsRelease) {
needsRelease = false;
// .. release the resource ...
}
}
}
When the resource is created it stores the identity hash code of the key,
and whenever use is called, it checks that the same key was provided.
Actually using the resource may require additional synchronization, but
for simplicity this is elided. The release method is responsible for releas-
ing the resource. It can either be called directly by the users of the re-
source when they have finished, or it will be called through the resource
manager when the key object is no longer referenced. Because we will
be using a separate thread to watch the reference queue, release has to
be synchronized and it has to be tolerant to being called more than once.
The actual resource manager looks like this:
public final class ResourceManager {
 
Search WWH ::




Custom Search