自定義快取系統,使用讀寫鎖
package cn.itcast.heima2;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class CacheDemo {//自定義快取系統,使用讀寫鎖
private Map<String, Object> cache = new HashMap<String, Object>();
public static void main(String[] args) {
// TODO Auto-generated method stub
}
//讀寫鎖
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public Object getData(String key){//獲取資料
rwl.readLock().lock();//開始讀
Object value = null;
try{
value = cache.get(key);
if(value == null){
rwl.readLock().unlock();//關閉讀鎖釋放寫鎖
rwl.writeLock().lock();
try{
if(value==null){
value = "aaaa";//實際失去queryDB();
}
}finally{
rwl.writeLock().unlock();//關閉寫鎖
}
rwl.readLock().lock();//釋放讀鎖
}
}finally{
rwl.readLock().unlock();//關閉讀鎖
}
return value;
}
}