我在下面的遗留项目中看到LRU缓存的实现,其中我有一个关于使用SoftReference
作为值对象而不是关键对象的问题。在Map中使用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;
}
}
GC回收了软可及对象存储应用程序是否即将达到内存不足(OOM)。 如果我应用相同的逻辑,则只应回收用于值的内存(因为仅为值对象创建软参考)。
但这里是我的问题是如何对应的密钥对象将从地图应用程序一次来到OOM中要删除的文件
// 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.
开头的注释。不应该用软参考包装 ?
cache.put(new SoftReference<K>(key), new SoftReference<V>(value));
'Key'预计将在尺寸较小的比较值,从而使按键软裁判并没有真正帮助不大 – 2014-10-29 07:14:18
是您发布的完整的类的代码? 'removeEldestEntry'方法意味着此映射中键的数量应限制为'cacheSize',但我没有看到它在任何地方执行。 – Eran 2014-10-29 07:18:08
@Eran这是完整的代码。 removeEldestEntry被内部调用,同时把操作 – user3198603 2014-10-29 10:28:55