1 package cn.lyy.hibernate.many2one;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.concurrent.locks.ReadWriteLock;
6 import java.util.concurrent.locks.ReentrantReadWriteLock;
7
8 public class MultiCacheDemo {
9
10 private Map<String, Object> cache = new HashMap<String,Object>();
11 public static void main(String args[]){
12
13 }
14
15 private ReadWriteLock rwl = new ReentrantReadWriteLock();
16 public Object getData(String key){
17 rwl.readLock().lock();
18 Object value = null;
19 try{
20 value = cache.get(key);
21 if(value == null){
22 rwl.readLock().unlock();
23 rwl.writeLock().lock();
24 try{
25 //因为如果同时又多个线程在读数据的话,可能会同时发现value
26 //为空,所以应该再在这里加一个if语句判断value是否为空
27 if(value == null){
28
29 value = "aaaa"; //实际是去queryDB();
30
31 }
32 }finally{
33 rwl.writeLock().unlock();
34 }
35 rwl.readLock().lock();
36 }
37 }finally{
38 rwl.readLock().unlock();
39 }
40 return value;
41 }
42 }