ReadWriteLock使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59public class CacheSystemTest { public static void main(String[] args) { MyCache cache = new MyCache(); ExecutorService threadpool = Executors.newCachedThreadPool(); for(int i =0;i<10;i++) { Thread t = new Thread(new Runnable() { @Override public void run() { cache.getData("testKey"); } }); threadpool.execute(t); } threadpool.shutdown(); } } class MyCache { private Map<String,Object> cacheStore = new HashMap<String, Object>(); private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public Object getData(String key) { Object data = null; //获取读锁,开始在缓存中查找我们想要的data readWriteLock.readLock().lock(); try { data = cacheStore.get(key); if(data==null) {//缓存中并未找到们想要的数据 readWriteLock.readLock().unlock(); //释放读锁 readWriteLock.writeLock().lock(); //开始查询数据库并且数据库中查询的数据写入缓存,获取写锁 try { if(data==null) { //query the data from the DB data = "data query from db"; cacheStore.put(key, data); } }finally { //数据库中数据写入缓存成功,释放写锁 readWriteLock.writeLock().unlock(); //并且此时需要重新获取读锁,否则下方finally里面释放读锁报错 readWriteLock.readLock().lock(); } } }finally { //缓存中就找到我们想要的数据,读取成功,释放读锁 readWriteLock.readLock().unlock(); } readWriteLock.writeLock().lock(); System.out.println(Thread.currentThread().getName() + " obtain the data from cache system: " + (String)data); readWriteLock.writeLock().unlock(); return data; } }
最后
以上就是淡然小馒头最近收集整理的关于缓存系统设计的全部内容,更多相关缓存系统设计内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复