读写锁缓存数据

public class LockTest {

    private static Map<String, Object> cacheMap = new HashMap<>();
    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public static void main(String[] args) {
        Object value = getKey("aaa");
        Object value2 = getKey("aaa");

        System.out.println(value);
        System.out.println(value2);
    }

    public static Object getKey(String key) {
        readWriteLock.readLock().lock();
        try {
            Object result = cacheMap.get(key);
            if (result != null) {
                return result;
            }
            readWriteLock.readLock().unlock();
            readWriteLock.writeLock().lock();
            try {
                result = cacheMap.get(key);
                if (result != null) {
                    return result;
                }
                // 模拟从db查询
                result = new Date();
                System.out.println("入库");
                cacheMap.put(key, result);
                return result;
            } finally {
                readWriteLock.writeLock().unlock();
                readWriteLock.readLock().lock();
            }
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页