MapMaker: 超级强大的 Map 构造工具
所处的包 package com.google.common.collect
MapMaker 是用来构造 ConcurrentMap 的工具类。为什么可以把 MapMaker 叫做超级强大?看了下面的例子你就知道了。首先,它可以用来构造ConcurrentHashMap:得到线程安全的hashMap
ConcurrentMap<String, Object> map1 = new MapMaker() .concurrencyLevel(8) .makeMap();
对应的源码为
@Override
public <K, V> ConcurrentMap<K, V> makeMap() {
if (!useCustomMap) {
return new ConcurrentHashMap<K, V>(getInitialCapacity(), 0.75f, getConcurrencyLevel());
}
return (nullRemovalCause == null)
? new MapMakerInternalMap<K, V>(this)
: new NullConcurrentMap<K, V>(this);
}
构造用各种不同 reference 作为 key 和 value 的 Map:
ConcurrentMap<String, Object> map2 = new MapMaker()
.weakValues()
.makeMap();
构造有自动移除时间过期项的 Map:存放30秒后移除,可以用于存放请求的场景
ConcurrentMap<String, Object> map3 = new MapMaker()
.expireAfterWrite(30, TimeUnit.SECONDS)
.makeMap();
构造有最大限制数目的 Map:限制存放数据
//Map size grows close to the 100, the map will evict
//entries that are less likely to be used again
ConcurrentMap<String, Object> map4 = new MapMaker()
.maximumSize(100)
.makeMap();
提供当 Map 里面 get 不到数据,它能够自动加入到 Map 的功能。这个功能当 Map 作为缓存的时候很有用 :
ConcurrentMap<String, Object> map5 = new MapMaker()
.makeComputingMap(
new Function<String, Object>() {
public Object apply(String key) {
return createObject(key);
}
private Object createObject(String key) {
// TODO Auto-generated method stub
return "";
}});
提供拥有以上所有特性的 Map:
ConcurrentMap<String, Object> mapAll = new MapMaker()
.concurrencyLevel(8)
.weakValues()
.expireAfterWrite(30, TimeUnit.SECONDS)
.maximumSize(100)
.makeComputingMap(
new Function<String, Object>() {
public Object apply(String key) {
return createObject(key);
}
private Object createObject(String key) {
// TODO Auto-generated method stub
return null;
}});