Skip to content

Instantly share code, notes, and snippets.

@shyiko
Created January 4, 2012 17:52
Show Gist options
  • Save shyiko/1561190 to your computer and use it in GitHub Desktop.
Save shyiko/1561190 to your computer and use it in GitHub Desktop.
SoftReferenceMap
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