实现一个简单能过时淘汰的的FIFO缓存

缓存简单实现

这里使用LinkedList和MashMap来实现一个能够过时淘汰的FIFO缓存,其中HashMap用于存储缓存数据,但是由于HashMap不能记录插入顺序,因此使用辅助数组LinkedList用于记录插入顺序。这个简单实现是非线程安全的。

import java.util.HashMap;
import java.util.LinkedList;
/**
 * 实现了一个LRU淘汰和过时淘汰的简单缓存
 * @author bhupam
 *
 * @param <T>
 */
public class MyCache<T>{
	private LinkedList<String> list=new LinkedList<>();
	private HashMap<String, CachedData<T>> map=new HashMap<>();
	private int size;
	public MyCache(int size) {
		this.size=size;
	}
	public T get(String key) {
		if(!map.containsKey(key)) return null;
		CachedData<T> cachedData=map.get(key);
		long now = System.currentTimeMillis();
		if(cachedData.getLife()>=now) {
			return cachedData.getData();
		}else {
			list.remove(key);
			map.remove(key);
			size--;
			return null;
		}
	}
	public void put(String key,T data,long expire ) {
		if(!map.containsKey(key)) {
			DoLRU();
			list.add(key);
			CachedData<T> cachedData=new CachedData<>(data, expire, System.currentTimeMillis());
			map.put(key, cachedData);
		}else {
			CachedData<T> cachedData=map.get(key);
			cachedData.setData(data);
			cachedData.setExpire(expire);
			cachedData.setLife(System.currentTimeMillis()+expire);
		}
	}
	private void DoLRU() {
		if(map.size()==this.size) {
			String removedEle = list.removeFirst();
			map.remove(removedEle);
		}
	}
	private static class CachedData<T> {
		private T data;
		private long expire;
		private long life;
		public CachedData(T data,long expire,long life) {
			this.expire=expire;
			this.data=data;
			this.life=System.currentTimeMillis()+expire;
		}
		public T getData() {
			return data;
		}
		public void setData(T data) {
			this.data = data;
		}
		public long getExpire() {
			return expire;
		}
		public void setExpire(long expire) {
			this.expire = expire;
		}
		public long getLife() {
			return life;
		}
		public void setLife(long life) {
			this.life = life;
		}
}
}

测试

public class CachedTest {
	public static void main(String[]args) throws InterruptedException {
		MyCache<Integer> cache=new MyCache<>(5);
		for(int i=0;i<10;i++) {
			cache.put("key"+i, i, 1000);
		}
		System.out.println((cache.get("key1")==null)?"null":cache.get("key1"));
		System.out.println((cache.get("key9")==null)?"null":cache.get("key9"));
		Thread.sleep(2000);
		System.out.println((cache.get("key9")==null)?"null":cache.get("key9"));
	}
}

结果

null
9
null
posted @ 2018-08-15 19:54  bhupam  阅读(352)  评论(0)    收藏  举报