用readWriteLock实现一个缓存

class Cache<K,V>{
  final Map<K,V> m =
    new HashMap<>();
  final ReadWriteLock rwl =
    new ReentrantReadWriteLock();
  //读🔒
  final Lock r = rwl.readLock();
  //写🔒
  final Lock w = rwl.writeLock();
  //读缓存
  V get(K key){
    r.lock();
    try{
      return m.get(key);
    }finally{
      r.unlock();
    }
  }

  //写缓存
  V put(String key, Data v){
    w.lock();
    try{
      return m.put(key, v);
    }finally{
      w.unlock();
    }
  }
}

  

double check查询缓存

class Cache<K,V>{
  final Map<K,V> m = new HashMap<>();
  final ReaderWriterLock = new RenterantReaderWriterLock();
  final Lock r = rwl.readLock();
  final Lock w = rwl.writerLock();
  
  V get(K key){
    V v = null;
    //读缓存
    r.lock();
    try{
      v = m.get(key);
    }finally{
      r.unlock();
    }
    //缓存存在,返回数据
    if(v != null){
      return v;
    }
    //缓存不存在
    w.lock();
    try{
      //再次验证
      //其他线程可能已经查询过数据库
      v = get(key);
      if(v == null){
        //获取v
        m.put(key, v);
      }
    }finally{
      w.unlock();
    }
    return v;
  }
}

  

 

posted on 2019-04-09 18:41  张小泽的小号  阅读(147)  评论(0编辑  收藏  举报

导航