123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- package cn.minbb.iot.util;
- import java.util.HashMap;
- // 链表 + HashMap 容器实现
- public class LRUCache<K, V> {
- private int cacheCapacity;
- private HashMap<K, CacheNode> caches;
- private CacheNode first;
- private CacheNode last;
- public LRUCache(int size) {
- this.cacheCapacity = size;
- caches = new HashMap<>(size);
- }
- public synchronized void put(K k, V v) {
- CacheNode node = caches.get(k);
- if (node == null) {
- if (caches.size() >= cacheCapacity) {
- caches.remove(last.key);
- removeLast();
- }
- node = new CacheNode();
- node.key = k;
- }
- node.value = v;
- moveToFirst(node);
- caches.put(k, node);
- }
- public synchronized Object get(K k) {
- CacheNode node = caches.get(k);
- if (node == null) {
- return null;
- }
- moveToFirst(node);
- return node.value;
- }
- public synchronized Object remove(K k) {
- CacheNode node = caches.get(k);
- if (node != null) {
- if (node.pre != null) {
- node.pre.next = node.next;
- }
- if (node.next != null) {
- node.next.pre = node.pre;
- }
- if (node == first) {
- first = node.next;
- }
- if (node == last) {
- last = node.pre;
- }
- }
- return caches.remove(k);
- }
- public synchronized void clear() {
- first = null;
- last = null;
- caches.clear();
- }
- private void moveToFirst(CacheNode node) {
- if (first == node) {
- return;
- }
- if (node.next != null) {
- node.next.pre = node.pre;
- }
- if (node.pre != null) {
- node.pre.next = node.next;
- }
- if (node == last) {
- last = last.pre;
- }
- if (first == null || last == null) {
- first = last = node;
- return;
- }
- node.next = first;
- first.pre = node;
- first = node;
- first.pre = null;
- }
- private void removeLast() {
- if (last != null) {
- last = last.pre;
- if (last == null) {
- first = null;
- } else {
- last.next = null;
- }
- }
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- CacheNode node = first;
- while (node != null) {
- sb.append(String.format("%s:%s ", node.key, node.value));
- node = node.next;
- }
- return sb.toString();
- }
- class CacheNode {
- CacheNode pre;
- CacheNode next;
- Object key;
- Object value;
- CacheNode() {
- // 无参构造
- }
- }
- }
|