实现缓存一些数据到本地,避免重复查询数据库,对数据库造成压力,代码如下:

package threadLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; 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;
}
}
05-08 15:34