Advertisement
absolute100

LRU multithreaded

Feb 12th, 2017
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.util.concurrent.ConcurrentHashMap;
  2. import java.util.concurrent.ConcurrentLinkedQueue;
  3. public class LRUCache<K, V> {
  4.     private final int capacity;
  5.     private ConcurrentLinkedQueue<K> queue;
  6.     private ConcurrentHashMap<K, V> map;
  7.     public LRUCache(final int capacity) {
  8.         this.capacity = capacity;
  9.         this.queue    = new ConcurrentLinkedQueue<K>();
  10.         this.map    = new ConcurrentHashMap<K, V>(capacity);
  11.     }
  12.  
  13.     //Check whether the items exists in the cache. Returns null if key doesn't exists in the cache.
  14.     public V get(final K key) {
  15.         V val = map.get(key);
  16.         if(val != null) {
  17.             queue.remove(key);
  18.             queue.add(key); // add to tail, note: queue head is least.
  19.                             // the same key can be added multiple times
  20.         }
  21.         return val;
  22.     }
  23.  
  24.     // Add new val to the LRU Cache. If the key already exists, the key will be promoted to the front of the cache.
  25.     // Neither the key nor the val can be null.
  26.     public synchronized void set(final K key, final V val) {
  27.         if(key == null || val == null) {
  28.             throw new NullPointerException();
  29.         }
  30.         if (map.containsKey(key)) {
  31.             queue.remove(key);
  32.         }
  33.         while (queue.size() >= capacity) {
  34.             K expiredKey = queue.poll(); // remove the head.
  35.             if (expiredKey != null) {
  36.                 map.remove(expiredKey);
  37.             }
  38.         }
  39.         queue.add(key);
  40.         map.put(key, val);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement