import java.util.concurrent.ConcurrentHashMap;public class LRUCache { private ConcurrentHashMaphashMap = new ConcurrentHashMap<>(); private int capacity;//容量 private LRUNode head;//头 private LRUNode tail;//尾 /** * 设置缓存 * * @param key 键 * @param value 值 */ public void set(String key, Object value) { LRUNode node = hashMap.get(key); if (node != null) { node.value = value; remove(node, false); } else { node = new LRUNode(key, value); if (hashMap.size() >= capacity) { // 每次容量不足时先删除最久未使用的元素 remove(tail, true); } hashMap.put(key, node); } // 将刚添加的元素设置为head setHead(node); } /** * 取缓存 * * @param key 键 * @return 值 */ public Object get(String key) { LRUNode node = hashMap.get(key); if (node != null) { // 将刚操作的元素放到head remove(node, false); setHead(node); return node.value; } return null; } private void setHead(LRUNode node) { // 先从链表中删除该元素 if (head != null) { node.next = head; head.prev = node; } head = node; if (tail == null) { tail = node; } } // 从链表中删除此Node,此时要注意该Node是head或者是tail的情形 private void remove(LRUNode node, boolean flag) { if (node.prev != null) { node.prev.next = node.next; } else { head = node.next; } if (node.next != null) { node.next.prev = node.prev; } else { tail = node.prev; } node.next = null; node.prev = null; if (flag) { hashMap.remove(node.key); } } public LRUCache(int capacity) { this.capacity = capacity; } private class LRUNode { String key; Object value; LRUNode prev; LRUNode next; private LRUNode(String key, Object value) { this.key = key; this.value = value; } }}复制代码