Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
51 lines (48 loc) · 1.75 KB

File metadata and controls

51 lines (48 loc) · 1.75 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package ThreadTest;
import java.util.Map;
import java.util.concurrent.*;
/*
* 线程安全的一个缓存器
* */
interface Compute<K,V>{
V compute(K arg) throws InterruptedException;
}
public class Memoizer<K,V> implements Compute<K,V>{
private final Map<K, Future<V>> cache=new ConcurrentHashMap<>();
/*
*使用 Future<V> 是为了 避免重复开销大的计算,使用线程的返回值任务Callable
* */
private final Compute<K,V> compute; //不同的计算方法
Memoizer(Compute<K,V> compute){
this.compute=compute;
}
@Override
public V compute(K arg) throws InterruptedException {
while(true){
Future<V> flag=cache.get(arg);
if (flag==null){
Callable<V> result=new Callable<V>() {
@Override
public V call() throws Exception {
return compute.compute(arg);
}
};
FutureTask<V> ft=new FutureTask<>(result);
flag=cache.putIfAbsent(arg, ft); //CurrentHashMap 的指定原子操作,避免“先检查后运行”线程不安全场景的出现
if (flag==null){
flag= ft;
ft.run();
}
}
try{
return flag.get();
//FutureTask<V> 是实现了callable接口的任务,在线程中执行后的返回值,如果线程在执行或者未开始,就陷入阻塞状态
// 直到任务执行完成,才有了返回值
}catch (CancellationException e){
cache.remove(arg,flag);
} catch (ExecutionException e){
e.printStackTrace();
}
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.