美文网首页
自己动手写ReentrantReadWriteLock

自己动手写ReentrantReadWriteLock

作者: 不将就51y | 来源:发表于2018-01-06 22:43 被阅读0次

    ReentrantLock实现缓存主要逻辑如下:

    public class CacheReadWriteLock {
    
        private final static Map<String, String> localCache = new HashMap<>();
    
        private final static ReadWriteLock readWritelock = new ReentrantReadWriteLock();
    
        private final static Lock readLock = readWritelock.readLock();
    
        private final static Lock WriteLock = readWritelock.writeLock();
    
        private CacheReadWriteLock() {
        }
    
        public static String getValue(String key) {
            String value = getCache(key);
            if (value == null) {
                value = "hello"; //query DB
                value = putCache(key, value);
            }
            return value;
        }
    
        public static String putCache(String key, String value) {
            WriteLock.lock();
            try {
                return localCache.putIfAbsent(key, value);
            } finally {
                WriteLock.unlock();
            }
        }
    
        public static String getCache(String key) {
            readLock.lock();
            try {
                return localCache.get(key);
            } finally {
                readLock.unlock();
            }
        }
    }
    
    

    ReentrantLock和ReentrantReadWriteLock实现本地缓存?

    相关文章

      网友评论

          本文标题:自己动手写ReentrantReadWriteLock

          本文链接:https://www.haomeiwen.com/subject/hkuunxtx.html