public class FIFOCache <K,V>{
//定义缓存最大容量
private int maxSize;
//定义当前缓存容量
private int curSize;
//定义用鱼存放缓存的key
private LinkedList<K> cacheKey;
//用于存放缓存的value
private HashMap<K,V> cacheValue;
//读写锁,保证线程安全性
private Lock lock = new ReentrantLock();
//构造函数
public FIFOCache(int maxSize) {
this.maxSize = maxSize;
this.curSize = 0;
this.cacheKey = new LinkedList<K>();
this.cacheValue = new HashMap<K, V>();
}
//向缓存中插入key-value
public void put(K key,V value){
//加锁
lock.lock();
try {
//如果缓存已满,则删除最老的key
if (maxSize == curSize) {
K oldKey = cacheKey.removeFirst();
cacheValue.remove(oldKey);
curSize--;
}
//插入新的key-value
cacheKey.add(key);
cacheValue.put(key,value);
curSize++;
}finally {
//解锁
lock.unlock();
}
}
// 查询指定key的value
public V get(K key) {
return cacheValue.get(key);
}
public void printKeys() {
System.out.println(this.cacheKey.toString());
}
public static void main(String[] args) {
FIFOCache<String,String> cache = new FIFOCache<>(5);
cache.put("A", "任务A");
cache.put("B", "任务B");
cache.put("C", "任务C");
cache.put("D", "任务D");
cache.put("E", "任务E");
cache.printKeys();
cache.put("F", "任务F");
cache.printKeys();
System.out.println("G=" + cache.get("G"));
System.out.println("C=" + cache.get("C"));
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。