package com.fenxiang.jiyajie;java
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;dom
public class CacheTest {get
private static Map<String,Object> cache = new HashMap<String,Object>();
public static void main(String[] args) {
}it
private ReadWriteLock rtl = new ReentrantReadWriteLock();//讀寫鎖
public Object getData(String key){
rtl.readLock().lock();
Object data = null;
try{
data = cache.get(key);
if(data == null){
rtl.readLock().unlock();
rtl.writeLock().lock();
try{
if(data == null){//雙重檢查,避免等待的多個寫鎖重複寫入數據
data ="DB";
}
}finally{
rtl.readLock().unlock();//在finally 中釋放讀鎖
}
rtl.readLock().lock();
}
}finally{
rtl.readLock().unlock();//在finally 中釋放讀鎖
}
return data;
}
}
class