代码实现一个Lrucache

/**伪代码实现一个lru缓存 关键  1、linkedhashmap 2、超时时间 value值要包装成一个 包含 过期时间的对象  3、*/


class BlockingLinkedHashmap<k, v> implemnts LinkedHashMap<k, v>{
	private ReentrantLock lock;


	private v get(k key){
		try{
			lock.lock();
			return super.get(key);
		}finally{
			lock.unlock();
		}

	}

	//下面省略好多getset 主要是加个lock


}

class ValueWrapper<v>{
	private v value;

	private long timeout;

	private Date c;

	public ValueWrapper(v value){

	}

	public ValueWrapper(v value, long tiemout){
		this.value = value;
		this.timeout = time;
		this.updateTime = new Date();
	}

	public v getValue(){
		if(timeout !=null ){
			Date now = new Date();
			updateTime = now;
			if(now.getTime - updateTime > timeout){
				return null;
			}
		}
		return v;
	}
}


class LruCache<k, v>{
 
 private  BlockingLinkedHashmap<k, v> map ;
	
	init(){
	map = new BlockingLinkedHashmap();

	}


	public void set(k key, v value, long timeout){
		map.put(key, new ValueWrapper<v>(value, timeout));
	}



	public void set(k key, v value){
		map.put(key, new ValueWrapper<v>(value));
	}

	public v get(k key){
	ValueWrapper<v> valueWrapper;
	valueWrapper = map.remove(key);
		if(valueWrapper == null){
			return null;
		}else{
			return valueWrapper.getValue();
		}

	}


}

 

代码实现一个Lrucache

上一篇:基于linux参数优化tcp三次握手与四次挥手


下一篇:oracle各服务说明及cmd启动启动命令