基于LinkedHashMap的LRU缓存实现(FIFO亦可)

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* @author wh445306
* @version 1.0
* @Desciption:LRUCache 参考:https://www.cnblogs.com/lzrabbit/p/3734850.html
* @date 2021-01-06 18:06
*/
public class LRUCache <K, V>{
private final int MAX_CACHE_SIZE;
private final float DEFAULT_LOAD_FACTORY = 0.75f;
LinkedHashMap<K, V> map;
public LRUCache(int cacheSize) {
MAX_CACHE_SIZE = cacheSize;
int capacity = (int)Math.ceil(MAX_CACHE_SIZE / DEFAULT_LOAD_FACTORY) + 1;
/*
* HashMap负载因子默认即为0.75,是一个折衷的取值
* 第三个参数设置为true,代表linkedlist按访问顺序排序,可作为LRU缓存
* 第三个参数设置为false,代表按插入顺序排序,可作为FIFO缓存
*/
map = new LinkedHashMap<K, V>(capacity, DEFAULT_LOAD_FACTORY, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > MAX_CACHE_SIZE;
}
};
}
public synchronized void put(K key, V value) {
map.put(key, value);
}
public synchronized V get(K key) {
return map.get(key);
}
public synchronized void remove(K key) {
map.remove(key);
}
public synchronized Set<Map.Entry<K, V>> getAll() {
return map.entrySet();
}
public synchronized int size() {
return map.size();
}
public synchronized void clear() {
map.clear();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<K, V> entry : map.entrySet()) {
sb.append(String.format("%s: %s ", entry.getKey(), entry.getValue()));
}
return sb.toString();
}
//测试
public static void main(String[] args) {
LRUCache<Integer, Integer> lru = new LRUCache<>(5);
lru.put(1, 1);
lru.put(2, 2);
lru.put(3, 3);
System.out.println(lru);
lru.get(1);
System.out.println(lru);
lru.put(4, 4);
lru.put(5, 5);
lru.put(6, 6);
System.out.println(lru);
}
}

效果:

 

posted @   IT情深  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示