publicclassLruCache<K, V> {
privatefinal LinkedHashMap<K, V> map;
/** Size of this cache in units. Not necessarily the number of elements. */privateint size;
privateint maxSize;
privateint putCount;
privateint createCount;
privateint evictionCount;
privateint hitCount;
privateint missCount;
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this cache.
*/publicLruCache(int maxSize){
if (maxSize <= 0) {
thrownew IllegalArgumentException("maxSize <= 0");
}
this.maxSize = maxSize;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/publicfinal V put(K key, V value){
if (key == null || value == null) {
thrownew NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
putCount++;
size += safeSizeOf(key, value);
previous = map.put(key, value);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
/**
* 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.
*/publicvoidtrimToSize(int maxSize){
while (true) {
K key;
V value;
synchronized (this) {
if (size < 0 || (map.isEmpty() && size != 0)) {
thrownew IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
//只要当前size<= maxSize 就结束循环if (size <= maxSize || map.isEmpty()) {
break;
}
// 获取这个对象,然后从map中移除掉,保证size<=maxSize
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
注释:Remove the eldest entries until the total of remaining entries is at or below the requested size 大概意思是说:清除时间最久的对象直到剩余缓存对象的大小小于设置的大小。没错是我们想找的。