我在一个遗留项目中看到了 LRU 缓存的下面实现,我SoftReference
对值对象的使用有疑问,但对关键对象没有疑问。
这是实现
public class LRUCacheImpl<K, V> implements LRUCache<K, V> {
// SoftReference is used for a memory friendly cache.
// The value will be removed under memory shortage situations and
// the keys of the values will be removed from the cache map.
private final Map<K, SoftReference<V>> cache;
public LRUCacheImpl(final int cacheSize) {
// 'true' uses the access order instead of the insertion order.
this.cache = new LinkedHashMap<K, SoftReference<V>> (cacheSize, 0.75f, true) {
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(Map.Entry<K, SoftReference<V>> eldest) {
// When to remove the eldest entry i.e. Least Recently Used (i.e. LRU) entry
return size() > cacheSize; // Size exceeded the max allowed.
}
};
}
@Override
public V put(K key, V value) {
SoftReference<V> previousValueReference = cache.put(key, new SoftReference<V>(value));
return previousValueReference != null ? previousValueReference.get() : null;
}
@Override
public V get(K key) {
SoftReference<V> valueReference = cache.get(key);
return valueReference != null ? valueReference.get() : null;
}
}
如果应用程序即将达到 OutOfMemory(OOM),GC 会为可软访问对象回收内存。如果我应用相同的逻辑,则只应回收值的内存(因为仅为值对象创建软引用)。
但这是文件开头的注释
// SoftReference is used for a memory friendly cache. // The value will be removed under memory shortage situations and // the keys of the values will be removed from the cache map.
我的问题是一旦应用程序到达 OOM,将如何从地图中删除相应的关键对象。密钥不应该也用软引用包装吗?
cache.put(new SoftReference<K>(key), new SoftReference<V>(value));