1. 程式人生 > >Java -- 讀寫鎖

Java -- 讀寫鎖

對於讀多寫少的場景,我們此時應該允許讀鎖的多次重入,提高讀操作的併發性,在這種情況下,我們將讀寫鎖分離。

 /**
     * 執行緒安全的local cache demo
     */
    class LocalCache {
        private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        private Lock writeLock = lock.writeLock();
        private Lock readLock = lock.readLock();

        private Map<String, String> data = new HashMap<>();

        public String get(String key) {
            readLock.lock();
            try {
                if (data.containsKey(key)) {
                    return data.get(key);
                }
                return "";
            } finally {
                readLock.unlock();
            }
        }

        public void set(String key, String value) {
            writeLock.lock();
            try {
                data.put(key, value);
            } finally {
                writeLock.unlock();
            }
        }

        public void clear() {
            writeLock.lock();
            try {
                data.clear();
            } finally {
                writeLock.unlock();
            }
        }
    }