/
LockHang.java
76 lines (63 loc) · 2.25 KB
/
LockHang.java
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package guava;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class LockHang {
private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private static int cacheMaxSize = 10;
/**
* 创建一个带有RemovalListener监听的缓存
*/
private static Cache<Integer, Integer> cache;
public static void main(String[] args) {
cacheInit();
putCache();
readWork();
System.exit(0);
}
private static void cacheInit() {
cache = CacheBuilder.newBuilder()
.removalListener(new MyRemovalListener()).maximumSize(cacheMaxSize).build();
}
private static void putCache() {
for (int i = 0; i < cacheMaxSize; i++) {
cache.put(i, i);
}
}
private static void readWork() {
// get read lock
lock.readLock().lock();
System.out.println("Thread={}" + Thread.currentThread() + " get read lock");
try {
// do something
cache.invalidate(1);
// 这个函数有可能触发部分cache remove操作,所以也会造成当前线程卡死
cache.getIfPresent(1);
} finally {
lock.readLock().unlock();
System.out.println("Thread={}" + Thread.currentThread() + " unlock the read lock");
}
}
/**
* 创建一个监听器,当cache被remove的时候,需要加写锁做是一些事情。
*/
private static class MyRemovalListener implements RemovalListener<Integer, Integer> {
@Override
public void onRemoval(RemovalNotification<Integer, Integer> notification) {
System.out.println("Thread={}" + Thread.currentThread() + " try to get write lock");
lock.writeLock().lock();
System.out.println("Thread={}" + Thread.currentThread() + " get write lock");
try {
String tips = String
.format("key=%s,value=%s,reason=%s was removed", notification.getKey(),
notification.getValue(), notification.getCause());
System.out.println(tips);
} finally {
lock.writeLock().unlock();
System.out.println("Thread={}" + Thread.currentThread() + " unlock the write lock");
}
}
}
}