import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class CatchDemo {
private Map<String, Object> cache = new HashMap<String, Object>();
public static void main(String[] args) {
}
//ReadWriteLock
//读锁与读锁不互斥,读锁与写锁,写所欲写锁互斥
// 线程安全
// 向数据库查询数据时,先查缓存系统,若有,则返回
// 若没有,则从数据库查询数据写入缓存,再读取
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public /* synchronized */ Object getData(String key) {
rwl.readLock().unlock();
Object obj = null;
try {
obj = cache.get(key);
if (obj == null) {
rwl.readLock().unlock();
rwl.writeLock().lock();
try {
if(obj == null)
obj = "aaa";// 实际上是queryDB
} finally {
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
rwl.readLock().unlock();
}
return obj;
}
}
转载请注明原文地址: https://ju.6miu.com/read-1125997.html