/** Caches {@code Bitmap} for {@code key}. The Bitmap is moved to the head of the queue. */@Overridepublicfinalbooleanput(String key, Bitmap value) {
if (key == null || value == null) {
thrownew NullPointerException("key == null || value == null");
}
synchronized (this) {
size += sizeOf(key, value);
Bitmap previous = map.put(key, value);
if (previous != null) {
size -= sizeOf(key, previous);
}
}
trimToSize(maxSize);
returntrue;
}
/**
* Remove the eldest entries until the total of remaining entries is at or below the requested size.
*
* @param maxSize the maximum size of the cache before returning. May be -1 to evict even 0-sized elements.
*/privatevoidtrimToSize(int maxSize) {
while (true) {
String key;
Bitmap value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
thrownew IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!");
}
if (size <= maxSize || map.isEmpty()) {
break;
}
Map.Entry<String, Bitmap> toEvict = map.entrySet().iterator().next();
if (toEvict == null) {
break;
}
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= sizeOf(key, value);
}
}
}
3.FuzzyKeyMemoryCache:这个是一个key等价删除策略,在构造器中穿一个Comparator参数进来,重写public int compare(T lhs, T rhs);这个方法,这种缓存会把已经缓存的key和将要缓存的key进行自己实现定义的方式进行对比,如果出现了这种等价就删除掉第一个对应的entry。如果没有找到就不用删除。核心代码 :
@Overridepublicbooleanput(String key, Bitmap value) {
// Search equal key and remove this entrysynchronized (cache) {
String keyToRemove = null;
for (String cacheKey : cache.keys()) {
if (keyComparator.compare(key, cacheKey) == 0) {
keyToRemove = cacheKey;
break;
}
}
if (keyToRemove != null) {
cache.remove(keyToRemove);
}
}
return cache.put(key, value);
}