线程安全的 LRUCache 实现

为什么80%的码农都做不了架构师?>>>   hot3.png

Java实现线程安全的 LRU 缓存:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class LRUCache {

 private final int maxSize;

 private ConcurrentHashMap map;

 private ConcurrentLinkedQueue queue;

 public LRUCache(final int maxSize) {
  this.maxSize = maxSize;
  map = new ConcurrentHashMap(maxSize);
  queue = new ConcurrentLinkedQueue();
 }

 public void put(final K key, final V value) {
  if (map.containsKey(key)) {
   // remove the key from the FIFO queue
   queue.remove(key);
  }

  while (queue.size() >= maxSize) {
   K oldestKey = queue.poll();
   if (null != oldestKey) {
    map.remove(oldestKey);
   }
  }
  queue.add(key);
  map.put(key, value);
 }

 public V get(final K key) {

  if (map.containsKey(key)) {
   // remove from queue and add it again in FIFO queue
   queue.remove(key);
   queue.add(key);
  }
  return map.get(key);
 }
}

 

转载于:https://my.oschina.net/jsan/blog/3041450

你可能感兴趣的:(线程安全的 LRUCache 实现)