我在下面的遺留項目中看到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