Skip to content

Instantly share code, notes, and snippets.

@makazeu
Created December 5, 2018 05:55
Show Gist options
  • Save makazeu/b23da357644088cd403d8e9ff8f88ce4 to your computer and use it in GitHub Desktop.
Save makazeu/b23da357644088cd403d8e9ff8f88ce4 to your computer and use it in GitHub Desktop.
Java LRU Cache
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache<K, V> {
private static final float HASH_TABLE_LOAD_FACTOR = 0.75f;
private LinkedHashMap<K, V> map;
private int cacheSize;
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math.ceil(cacheSize / HASH_TABLE_LOAD_FACTOR) + 1;
map = new LinkedHashMap<K, V>(hashTableCapacity, HASH_TABLE_LOAD_FACTOR, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
public synchronized V get(K key) {
return map.get(key);
}
public synchronized void put(K key, V value) {
map.put(key, value);
}
public synchronized void clear() {
map.clear();
}
public synchronized int usedSized() {
return map.size();
}
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<>(map.entrySet());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment