标签:降级锁 readwritelock 缓存 并发 hashmap
本文可作为传智播客《张孝祥-Java多线程与并发库高级应用》的学习笔记。
这一节我们做一个缓存系统。
public class CacheDemo { private Map<String, Object> cache = new HashMap<String, Object>(); public static void main(String[] args) { CacheDemo cd = new CacheDemo(); System.out.println("ss "+cd.getData2("ss")); System.out.println("ss "+cd.getData2("ss")); System.out.println("mm "+cd.getData2("mm")); System.out.println("mm "+cd.getData2("mm")); } public Object getData2(String key){ Object o=cache.get(key); if (o==null) { //标识1 System.out.println("第一次查 没有"+key); o=Math.random(); //实际上从数据库中获得 cache.put(key, o); } return o; } }运行结果:
}
private Lock l=new ReentrantLock(); //l作为CacheDemo的成员变量 public Object getData3(String key) { l.lock(); Object o=null; try { o = cache.get(key); if (o == null) { // 标识1 System.out.println("第一次查 没有" + key); o = Math.random(); // 实际上从数据库中获得 cache.put(key, o); } } finally { l.unlock(); } return o; }第三版可以吗?
为什么,自己想。
对同一个线程,可以在加了读锁后,没有解开读锁前,再加写锁吗?
换句话说,下面的代码会停吗?
public class CacheDemo { private Map<String, Object> cache = new HashMap<String, Object>(); private ReadWriteLock rwl = new ReentrantReadWriteLock(); public static void main(String[] args) { CacheDemo cd = new CacheDemo(); cd.getData2(); } public void getData2(){ rwl.readLock().lock(); System.out.println(1); rwl.writeLock().lock(); System.out.println(2); rwl.readLock().unlock(); System.out.println(3); rwl.writeLock().unlock(); System.out.println(4); } }亲自试一下,控制台输出1后,程序就不动了。
public static void main(String[] args) { CacheDemo cd = new CacheDemo(); System.out.println("ss "+cd.getData4("ss")); System.out.println("ss "+cd.getData4("ss")); System.out.println("mm "+cd.getData4("mm")); System.out.println("mm "+cd.getData4("mm")); } public Object getData4(String key){ rwl.readLock().lock(); Object o=null; try { o=cache.get(key); if (o==null) { System.out.println("第一次查 没有"+key); rwl.readLock().unlock(); //标识4 rwl.writeLock().lock(); try { if(value==null){ //标识0 value = "aaaa";//实际调用 queryDB(); cache.put(key,value); } } finally { rwl.writeLock().unlock(); } rwl.readLock().lock(); //标识1 } }finally { rwl.readLock().unlock(); //标注2 } return o; }结果
mm 0.8534424949014686
这个还有三个问题
class CachedData { Object data; volatile boolean cacheValid; final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); void processCachedData() { rwl.readLock().lock(); if (!cacheValid) { // Must release read lock before acquiring write lock rwl.readLock().unlock(); rwl.writeLock().lock(); try { // Recheck state because another thread might have // acquired write lock and changed state before we did. if (!cacheValid) { data = ... cacheValid = true; } // Downgrade by acquiring read lock before releasing write lock rwl.readLock().lock(); } finally { rwl.writeLock().unlock(); // Unlock write, still hold read } } try { use(data); } finally { rwl.readLock().unlock(); } } }
标签:降级锁 readwritelock 缓存 并发 hashmap
原文地址:http://blog.csdn.net/dlf123321/article/details/42933331