Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentLinkedQueue;
- public class LRUCache<K, V> {
- private final int capacity;
- private ConcurrentLinkedQueue<K> queue;
- private ConcurrentHashMap<K, V> map;
- public LRUCache(final int capacity) {
- this.capacity = capacity;
- this.queue = new ConcurrentLinkedQueue<K>();
- this.map = new ConcurrentHashMap<K, V>(capacity);
- }
- //Check whether the items exists in the cache. Returns null if key doesn't exists in the cache.
- public V get(final K key) {
- V val = map.get(key);
- if(val != null) {
- queue.remove(key);
- queue.add(key); // add to tail, note: queue head is least.
- // the same key can be added multiple times
- }
- return val;
- }
- // Add new val to the LRU Cache. If the key already exists, the key will be promoted to the front of the cache.
- // Neither the key nor the val can be null.
- public synchronized void set(final K key, final V val) {
- if(key == null || val == null) {
- throw new NullPointerException();
- }
- if (map.containsKey(key)) {
- queue.remove(key);
- }
- while (queue.size() >= capacity) {
- K expiredKey = queue.poll(); // remove the head.
- if (expiredKey != null) {
- map.remove(expiredKey);
- }
- }
- queue.add(key);
- map.put(key, val);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement