1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.properties.spi.config.cache.guava;
17
18 import java.util.Set;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.locks.Lock;
21 import java.util.concurrent.locks.ReentrantReadWriteLock;
22
23 import com.google.common.cache.Cache;
24
25
26
27
28
29
30
31 public final class GuavaDelegatingCache<K, V> implements
32 de.smartics.properties.spi.config.cache.Cache<K, V>
33 {
34
35
36
37
38
39
40
41
42 private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
43
44
45
46
47
48
49 private final Lock readLock = lock.readLock();
50
51
52
53
54
55
56 private final Lock writeLock = lock.writeLock();
57
58
59
60
61 private final Cache<K, V> cache;
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76 public GuavaDelegatingCache(final Cache<K, V> cache)
77 {
78 this.cache = cache;
79 }
80
81
82
83
84
85
86
87
88
89
90
91 @Override
92 public long size()
93 {
94 readLock.lock();
95 try
96 {
97 return cache.size();
98 }
99 finally
100 {
101 readLock.unlock();
102 }
103 }
104
105 @Override
106 public V get(final K key)
107 {
108 readLock.lock();
109 try
110 {
111 return cache.getIfPresent(key);
112 }
113 finally
114 {
115 readLock.unlock();
116 }
117 }
118
119 @Override
120 public void put(final K key, final V value)
121 {
122 writeLock.lock();
123 try
124 {
125 cache.put(key, value);
126 }
127 finally
128 {
129 writeLock.unlock();
130 }
131 }
132
133 @Override
134 public void put(final K key, final V value, final long updateIntervalInMs,
135 final TimeUnit milliseconds)
136 {
137 writeLock.lock();
138 try
139 {
140 cache.put(key, value);
141 }
142 finally
143 {
144 writeLock.unlock();
145 }
146 }
147
148 @Override
149
150 public void put(final K key, final V value, final int lifespan,
151 final TimeUnit lifespanTimeUnit, final int maxIdleTime,
152 final TimeUnit maxIdleTimeTimeUnit)
153 {
154 writeLock.lock();
155 try
156 {
157 cache.put(key, value);
158 }
159 finally
160 {
161 writeLock.unlock();
162 }
163 }
164
165
166
167 @Override
168 public V remove(final K key)
169 {
170 writeLock.lock();
171 try
172 {
173 final V returnValue = cache.getIfPresent(key);
174 cache.invalidate(key);
175 return returnValue;
176 }
177 finally
178 {
179 writeLock.unlock();
180 }
181 }
182
183 @Override
184 public Set<K> keySet()
185 {
186 readLock.lock();
187 try
188 {
189 return cache.asMap().keySet();
190 }
191 finally
192 {
193 readLock.unlock();
194 }
195 }
196
197 }