package com.ye;
import java.util.LinkedHashMap;
import java.util.Map;
class LRU<K, V> {
private float loadFactor = 0.75f;
private int cacheSize;
private LinkedHashMap<K, V> map;
public LRU(int cacheSize) {
this.cacheSize = cacheSize;
int capacity = (int) Math.ceil(cacheSize * loadFactor) + 1;
// new LinkedHashMap<K, V>(capacity, loadFactor, true) capacity:初始化大小 loadFactor:扩容因子 true:被访问元素,重新排第一(必须为true)
this.map = new LinkedHashMap<K, V>(capacity, loadFactor, true) {
//重写removeEldestEntry 当map 的元素大于,缓存大小,删除尾部元素
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > LRU.this.cacheSize;
}
};
}
//synchronized 加锁,避免同步问题
public synchronized Object get(K key) {
return map.get(key);
}
public synchronized V put(K key, V value) {
return map.put(key, value);
}
public synchronized void clear() {
map.clear();
}
public synchronized int size() {
return map.size();
}
public void print() {
System.out.println("=================");
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
}
}
public class LRUTest {
public static void main(String[] args) {
LRU lru = new LRU(3);
lru.put("1", "第1个");
lru.print();
lru.put("2", "第2个");
lru.put("3", "第3个");
lru.print();
lru.get("1");
lru.put("2", "第11个");
lru.put("4", "第4个");
lru.print();
}
}
测试结果:
=================
1:第1个
=================
1:第1个
2:第2个
3:第3个
=================
1:第1个
2:第11个
4:第4个