-
Notifications
You must be signed in to change notification settings - Fork 29
/
UseFutureTaskImplementedCache.java
59 lines (43 loc) · 1.39 KB
/
UseFutureTaskImplementedCache.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
package multithread;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;
/**
* 使用FutureTask来实现的高效缓存.
*/
public class UseFutureTaskImplementedCache {
class AccountCache {
private final ConcurrentHashMap<String, FutureTask<Account>> _cache;
public AccountCache() {
this._cache = new ConcurrentHashMap<>();
}
public Account get(String id) throws Exception {
FutureTask<Account> exists = _cache.get(id);
if (exists != null) {
// 结果已经存在或者正有人在计算
return exists.get();
}
FutureTask<Account> newTask = new FutureTask<Account>(new Callable<Account>() {
@Override
public Account call() throws Exception {
return _loadFromDB(id);
}
});
exists = _cache.putIfAbsent(id, newTask);
if (exists == null) {
// let me call it
newTask.run();
return newTask.get();
} else {
// someone has doing cal
return exists.get();
}
}
Account _loadFromDB(String id){
//load it...
return null;
}
}
class Account {
}
}