欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

guava MapMaker使用示例,guavamapmaker示例,MapMaker: 超级

来源: javaer 分享于  点击 47192 次 点评:96

guava MapMaker使用示例,guavamapmaker示例,MapMaker: 超级


MapMaker: 超级强大的 Map 构造工具

MapMaker 是用来构造 ConcurrentMap 的工具类。为什么可以把 MapMaker 叫做超级强大?看了下面的例子你就知道了。首先,它可以用来构造 ConcurrentHashMap:

 //ConcurrentHashMap with concurrency level 8  ConcurrentMap<String, Object> map1 = new MapMaker()     .concurrencyLevel(8)      .makeMap();

或者构造用各种不同 reference 作为 key 和 value 的 Map:

 //ConcurrentMap with soft reference key and weak reference value  ConcurrentMap<String, Object> map2 = new MapMaker()     .softKeys()     .weakValues()     .makeMap();

或者构造有自动移除时间过期项的 Map:

 //Automatically removed entries from map after 30 seconds since they are created  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 作为缓存的时候很有用 :

 //Create an Object to the map, when get() is missing in map  ConcurrentMap<String, Object> map5 = new MapMaker()     .makeComputingMap(       new Function<String, Object>() {         public Object apply(String key) {           return createObject(key);     }});

这些还不是最强大的特性,最厉害的是 MapMaker 可以提供拥有以上所有特性的 Map:

 //Put all features together!  ConcurrentMap<String, Object> mapAll = new MapMaker()     .concurrencyLevel(8)     .softKeys()     .weakValues()     .expireAfterWrite(30, TimeUnit.SECONDS)     .maximumSize(100)     .makeComputingMap(       new Function<String, Object>() {         public Object apply(String key) {           return createObject(key);      }});
相关栏目:

用户点评