盒子
盒子

构建高效可伸缩的缓存

1
2
3
4
5
@FunctionalInterface
public interface Computable<K, V> {

V compute(K key) throws InterruptedException;
}
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
76
77
78
/**
* 构建高效且可伸缩的缓存
*/
public class MemCache<K, V> implements Computable<K, V> {

private final ConcurrentHashMap<K, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<K, V> computable;

public MemCache(Computable<K, V> computable) {
this.computable = computable;
}

@Override
public V compute(K key) throws InterruptedException {
while (true) {
Future<V> f = cache.get(key);
if (f == null) {
Callable<V> callable = () -> {
return computable.compute(key);
};
FutureTask<V> task = new FutureTask<>(callable);
Future<V> ft = cache.putIfAbsent(key, task);
if (f == null) {
f = ft;
task.run();
}
}

try {
if (f != null) {
return f.get();
}
} catch (CancellationException e) {
cache.remove(key, f);
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
Computable<Integer, Integer> computable = (key) -> {
// 模拟费时计算过程
Thread.sleep(10000);
return key;
};
MemCache<Integer, Integer> memCache = new MemCache<>(computable);

CyclicBarrier cyclicBarrier = new CyclicBarrier(1, () -> {
for (int i = 0; i < 6; i++) {
new Thread(() -> {
try {
long startTime = System.currentTimeMillis();
memCache.compute(99);
long endTime = System.currentTimeMillis();
System.out.println("从缓存中取值线程执行时间为:" + (endTime - startTime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
});

new Thread(() -> {
try {
long startTime = System.currentTimeMillis();
memCache.compute(99);
long endTime = System.currentTimeMillis();
System.out.println("未从缓存中取值线程执行时间为:" + (endTime - startTime));
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}

执行结果
未从缓存中取值线程执行时间为:10010
从缓存中取值线程执行时间为:0
从缓存中取值线程执行时间为:0
从缓存中取值线程执行时间为:0
从缓存中取值线程执行时间为:0
从缓存中取值线程执行时间为:0
从缓存中取值线程执行时间为:0

支持一下
扫一扫,支持沈健
  • 微信扫一扫
  • 支付宝扫一扫