首页 > 代码库 > 缓存的写法 利用读写锁
缓存的写法 利用读写锁
public class CacheDemo {
private Map<String, Object> cache = new HashMap<String, Object>();
public static void main(String[] args) {
// TODO Auto-generated method stub
}
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public Object getData(String key){
rwl.readLock().lock();
Object value = http://www.mamicode.com/null;
try{
value = http://www.mamicode.com/cache.get(key);
if(value =http://www.mamicode.com/= null){
rwl.readLock().unlock();
rwl.writeLock().lock();
try{
if(value=http://www.mamicode.com/=null){
value = "http://www.mamicode.com/aaaa";//实际是去queryDB();
}
}finally{
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
}finally{
rwl.readLock().unlock();
}
return value;
}
}
缓存的写法 利用读写锁