java模拟数据库缓存
时间:2021-07-01 10:21:17
帮助过:48人阅读
public class CatheDemo {
private Map<String, Object> map =
new HashMap<String, Object>
();
private ReadWriteLock rwl =
new ReentrantReadWriteLock();
//定义读写锁
public Object getData(String key){
rwl.readLock().lock();
Object value =
null;
try {
value = map.
get(key);
if (value ==
null) {
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
if(value ==
null)
value =
"dqwdwqd";
//从数据库中查找数据
}
catch (Exception e) {
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
rwl.readLock().lock();
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
return value;
}
}
java模拟数据库缓存
标签:pre 压力 code map try private 写锁 模拟 nal