Created
December 5, 2018 05:55
-
-
Save makazeu/b23da357644088cd403d8e9ff8f88ce4 to your computer and use it in GitHub Desktop.
Java LRU Cache
This file contains hidden or 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
| 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