ReadWriteLock使用
public class CacheSystemTest {
public static void main(String[] args) {
MyCache cache = new MyCache();
ExecutorService threadpool = Executors.newCachedThreadPool();
for(int i =0;i<10;i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
cache.getData("testKey");
}
});
threadpool.execute(t);
}
threadpool.shutdown();
}
}
class MyCache {
private Map<String,Object> cacheStore = new HashMap<String, Object>();
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public Object getData(String key) {
Object data = null;
//获取读锁,开始在缓存中查找我们想要的data
readWriteLock.readLock().lock();
try {
data = cacheStore.get(key);
if(data==null) {//缓存中并未找到们想要的数据
readWriteLock.readLock().unlock(); //释放读锁
readWriteLock.writeLock().lock(); //开始查询数据库并且数据库中查询的数据写入缓存,获取写锁
try {
if(data==null) {
//query the data from the DB
data = "data query from db";
cacheStore.put(key, data);
}
}finally {
//数据库中数据写入缓存成功,释放写锁
readWriteLock.writeLock().unlock();
//并且此时需要重新获取读锁,否则下方finally里面释放读锁报错
readWriteLock.readLock().lock();
}
}
}finally {
//缓存中就找到我们想要的数据,读取成功,释放读锁
readWriteLock.readLock().unlock();
}
readWriteLock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " obtain the data from cache system: " + (String)data);
readWriteLock.writeLock().unlock();
return data;
}
}