自己动手写ReentrantReadWriteLock

2018-01-06  本文已影响0人  不将就51y

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实现本地缓存?

上一篇下一篇

猜你喜欢

热点阅读