模拟一个简单的缓存管理
public static void main(String[] args) {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Map<String, Object> map = new HashMap<>();
// 读锁,共享锁
ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
// 写锁,独占锁
ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
/**
* 读锁是共享锁,不会独占
* 写锁是独占锁,独占CPU
* 下面实现简单缓存功能,缓存存在,就直接读取,不存在,就写入缓存
*/
Thread[] threads = new Thread[20];
for (int i = 0; i < threads.length; i++) {
// 缓存的key
String key = String.valueOf(i % 5);
threads[i] = new Thread(() -> {
try {
// 读锁
readLock.lock();
// 缓存已存在,直接从缓存中读取
if (map.containsKey(key)) {
System.out.println("[读锁]缓存中存在key=" + key + "," + Thread.currentThread().getName() +
"拿到缓存中的值:" + map.get(key));
} else {
// 缓存不存在,先读锁解锁,然后加入写锁,
// 判断缓存是否存在,存在,直接读取,不存在,写入缓存
readLock.unlock();
// 写入缓存,先加写锁
try {
writeLock.lock();
if (!map.containsKey(key)) {
Thread.sleep(1000);
map.put(key, key);
System.out.println("[写锁]缓存中不存在key=" + key + "," + Thread.currentThread().getName() + "写入缓存中的值:" + key);
}
// 这里要注意:这里抢占读锁,是为了避免在上面的写锁释放以后被其他写锁独占,从而覆盖了值。
readLock.lock();
System.out.println("[写锁]缓存中存在key=" + key + "," + Thread.currentThread().getName() +
"拿到缓存中的值:" + map.get(key));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
writeLock.unlock();
}
}
} finally {
readLock.unlock();
}
});
threads[i].start();
}
}
效果:
[写锁]缓存中不存在key=0,Thread-0写入缓存中的值:0,时间:2020-09-18 17:16:39
[写锁]缓存中存在key=0,Thread-0拿到缓存中的值:0,时间:2020-09-18 17:16:39
[写锁]缓存中不存在key=1,Thread-1写入缓存中的值:1,时间:2020-09-18 17:16:40
[写锁]缓存中存在key=1,Thread-1拿到缓存中的值:1,时间:2020-09-18 17:16:40
[写锁]缓存中不存在key=2,Thread-2写入缓存中的值:2,时间:2020-09-18 17:16:41
[写锁]缓存中存在key=2,Thread-2拿到缓存中的值:2,时间:2020-09-18 17:16:41
[写锁]缓存中不存在key=4,Thread-4写入缓存中的值:4,时间:2020-09-18 17:16:42
[写锁]缓存中存在key=4,Thread-4拿到缓存中的值:4,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=0,Thread-5拿到缓存中的值:0,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=4,Thread-9拿到缓存中的值:4,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=1,Thread-6拿到缓存中的值:1,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=4,Thread-14拿到缓存中的值:4,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=1,Thread-11拿到缓存中的值:1,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=0,Thread-10拿到缓存中的值:0,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=0,Thread-15拿到缓存中的值:0,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=2,Thread-12拿到缓存中的值:2,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=2,Thread-17拿到缓存中的值:2,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=4,Thread-19拿到缓存中的值:4,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=1,Thread-16拿到缓存中的值:1,时间:2020-09-18 17:16:42
[读锁]缓存中存在key=2,Thread-7拿到缓存中的值:2,时间:2020-09-18 17:16:42
[写锁]缓存中不存在key=3,Thread-8写入缓存中的值:3,时间:2020-09-18 17:16:43
[写锁]缓存中存在key=3,Thread-8拿到缓存中的值:3,时间:2020-09-18 17:16:43
[写锁]缓存中存在key=3,Thread-3拿到缓存中的值:3,时间:2020-09-18 17:16:43
[写锁]缓存中存在key=3,Thread-13拿到缓存中的值:3,时间:2020-09-18 17:16:43
[写锁]缓存中存在key=3,Thread-18拿到缓存中的值:3,时间:2020-09-18 17:16:43
还没有评论,来说两句吧...