Created
January 4, 2012 17:52
-
-
Save shyiko/1561190 to your computer and use it in GitHub Desktop.
SoftReferenceMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Cache<K, V> { | |
private final Map<K, SoftReference<V>> map; | |
public Cache(final int cacheSize) { | |
map = Collections.synchronizedMap(new LinkedHashMap<K, SoftReference<V>>() { | |
@Override | |
protected boolean removeEldestEntry(java.util.Map.Entry<K, SoftReference<V>> eldest) { | |
return size() > cacheSize; | |
} | |
}); | |
} | |
public V put(K key, V value) { | |
SoftReference<V> previousValue = map.put(key, new SoftReference<V>(value)); | |
return previousValue != null ? previousValue.get() : null; | |
} | |
public V get(K key) { | |
SoftReference<V> valueReference = map.get(key); | |
return valueReference != null ? valueReference.get() : null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment