class CacheDemo{
Map<String,Object> cache = new HashMap<String,Object>();
public synchronized Object getData(String key){//synchronized避免多次查询数据库
Object data = cache.get(key);
if(data == null){
//去数据库查询queryDB
}
return data;
};
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public Object getData1(String key){//利用读写锁
readWriteLock.readLock().lock();
Object data = null;
try{
data = cache.get(key);
if(data == null){
readWriteLock.readLock().unlock();
readWriteLock.writeLock().lock();
try{
if(data == null)//防止写锁释放时,马上有写操作进来继续锁住写操作
data = "";//去数据库查询queryDB
}finally {
readWriteLock.writeLock().unlock();
}
readWriteLock.readLock().lock();
}
}finally {
readWriteLock.readLock().unlock();
}
return data;
};
}
缓存Cache设计
最新推荐文章于 2024-07-11 17:44:38 发布