Skip to content

Commit fb12625

Browse files
committed
新增:google Collection 的MapMaker使用
1 parent 6098bfb commit fb12625

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package org.javacore.colgoogle;
2+
3+
import com.google.common.base.Function;
4+
import com.google.common.collect.MapMaker;
5+
6+
import java.util.concurrent.ConcurrentMap;
7+
import java.util.concurrent.TimeUnit;
8+
9+
/**
10+
* Created by 子木 on 2016/2/20.
11+
*/
12+
public class MapMakerT0 {
13+
public static void main(String[] args) {
14+
/**
15+
* expiration(3, TimeUnit.SECONDS)设置超时时间为3秒
16+
*/
17+
ConcurrentMap<String , String> map = new MapMaker().concurrencyLevel(32).softKeys().weakValues()
18+
.expiration(3, TimeUnit.SECONDS).makeComputingMap(
19+
/**
20+
* 提供当Map里面不包含所get的项,可以自动加入到Map的功能
21+
* 可以将这里的返回值放到对应的key的value中
22+
*/
23+
new Function<String, String>() {
24+
public String apply(String s) {
25+
return "creating " + s + " -> Object";
26+
}
27+
}
28+
);
29+
30+
map.put("a","testa");
31+
map.put("b","testb");
32+
33+
System.out.println(map.get("a"));
34+
System.out.println(map.get("b"));
35+
System.out.println(map.get("c"));
36+
37+
try {
38+
// 4秒后,大于超时时间,缓存失效。
39+
Thread.sleep(4000);
40+
} catch (InterruptedException e) {
41+
e.printStackTrace();
42+
}
43+
44+
System.out.println(map.get("a"));
45+
System.out.println(map.get("b"));
46+
System.out.println(map.get("c"));
47+
}
48+
}

0 commit comments

Comments
 (0)