Java中的读写锁:
多个读锁不互斥, 读锁与写锁互斥, 写锁与写锁互斥, 这是由JVM自行控制的,我们只要上好相应的锁即可。
缓存的设计:
package com.cn.gbx; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class CacheDesign { private Map<String, Object> cache = new HashMap<String, Object>(); //对象锁的设计 // public synchronized Object getData(String key){ // Object value = null; // value = cache.get(key); // if (value == null) { // value = "queryDao"; // cache.put(key, value); // } // return value; // } //可重入锁的设计 static ReadWriteLock rwl = new ReentrantReadWriteLock(); public synchronized Object getData(String key){ Object value = null; rwl.readLock().lock(); try { value = cache.get(key); if (value == null) { rwl.readLock().unlock(); rwl.writeLock().lock(); try{ if (value == null) { //确保后边的线程不会重读写 value = "queryDao"; cache.put(key, value); } }finally{ rwl.writeLock().unlock(); } rwl.readLock().lock(); } }finally{ rwl.readLock().unlock(); } return value; } public static void main(String[] args) { } }