CacheMappublic class CacheMap extends WeakHashMap Like WeakHashMap, except that the keys of the n most
recently-accessed entries are kept as {@link SoftReference soft
references}. Accessing an element means creating it, or retrieving
it with {@link #get(Object) get}. Because these entries are kept
with soft references, they will tend to remain even if their keys
are not referenced elsewhere. But if memory is short, they will
be removed. |
Fields Summary |
---|
private final LinkedList | cache | private final int | nSoftReferences |
Constructors Summary |
---|
public CacheMap(int nSoftReferences)Create a CacheMap that can keep up to
nSoftReferences as soft references.
if (nSoftReferences < 0) {
throw new IllegalArgumentException("nSoftReferences = " +
nSoftReferences);
}
this.nSoftReferences = nSoftReferences;
|
Methods Summary |
---|
private void | cache(java.lang.Object key)
Iterator it = cache.iterator();
while (it.hasNext()) {
SoftReference sref = (SoftReference) it.next();
Object key1 = sref.get();
if (key1 == null)
it.remove();
else if (key.equals(key1)) {
// Move this element to the head of the LRU list
it.remove();
cache.add(0, sref);
return;
}
}
int size = cache.size();
if (size == nSoftReferences) {
if (size == 0)
return; // degenerate case, equivalent to WeakHashMap
it.remove();
}
cache.add(0, new SoftReference(key));
| public java.lang.Object | get(java.lang.Object key)
cache(key);
return super.get(key);
| public java.lang.Object | put(java.lang.Object key, java.lang.Object value)
cache(key);
return super.put(key, value);
|
|