package cn.lyy.hibernate.many2one; import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; public class MultiCacheDemo { private Map<String, Object> cache = new HashMap<String,Object>();
public static void main(String args[]){ } private ReadWriteLock rwl = new ReentrantReadWriteLock();
public Object getData(String key){
rwl.readLock().lock();
Object value = null;
try{
value = cache.get(key);
if(value == null){
rwl.readLock().unlock();
rwl.writeLock().lock();
try{
//因为如果同时又多个线程在读数据的话,可能会同时发现value
//为空,所以应该再在这里加一个if语句判断value是否为空
if(value == null){ value = "aaaa"; //实际是去queryDB(); }
}finally{
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
}finally{
rwl.readLock().unlock();
}
return value;
}
}