面试题之用伪代码设计缓存

package com.ThreadLearn.test;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
//面试题,设计一个缓存系统;用伪代码实现
public class CacheDemo {

	//存放对象的容器
	private Map map = new HashMap();
	//读写锁
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public Object getObject(String key) {
		
		Object obj = null;
		rwl.readLock().lock();
		try{
			
			if(map.get(key)==null){
				
				rwl.readLock().unlock();
				rwl.writeLock().lock();
				
				try{
					obj = readFromDB();
					
				}finally{
					rwl.writeLock().unlock();
				}
				rwl.readLock().lock();
				
			}else{
				
				obj = map.get(key);
			}
		}catch(Exception ex){
			
			ex.printStackTrace();
		}finally{
			
			rwl.readLock().unlock();
		}
		return obj;
	}
	
	public Object readFromDB(){
		
		//从数据库中读取数据,代码略
		return null;
	}
}


 

你可能感兴趣的:(JAVA)