Java高性能集合类 ConcurrentLinkedHashMap demo

来源:互联网 发布:火车票抢购软件 编辑:程序博客网 时间:2024/06/01 21:56

ConcurrentLinkedHashMap是java.util.LinkedHashMap的一个高性能实现。主要用于软件缓存。

ConcurrentLinkedHashMap 是google团队提供的一个容器。它有什么用呢?其实它本身是对
ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。详细介绍可以参见  
http://code.google.com/p/concurrentlinkedhashmap

https://github.com/ben-manes/concurrentlinkedhashmap

import java.util.Map;import java.util.concurrent.ConcurrentMap;import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;import com.googlecode.concurrentlinkedhashmap.EvictionListener;import com.googlecode.concurrentlinkedhashmap.Weighers;public class Test {public static void main(String[] args) {//test001();test002();}private static void test001() {EvictionListener<String, String> listener = new EvictionListener<String, String>() {@Overridepublic void onEviction(String key, String value) {System.out.println("Evicted key=" + key + ", value=" + value);}};ConcurrentMap<String, String> cache = new ConcurrentLinkedHashMap.Builder<String, String>().maximumWeightedCapacity(10).listener(listener).build();for (int i = 0; i < 150; i++) {int j = 1024;j = j + i;cache.put(String.valueOf(j), "nihao" + i);}for (Map.Entry<String, String> entry : cache.entrySet()) {String key = entry.getKey();String value = entry.getValue();System.out.println(key + "====" + value);}System.out.println(cache.get("1025"));cache.remove("1026");}/**ConcurrentLinkedHashMap 是google团队提供的一个容器。它有什么用呢?其实它本身是对ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。详细介绍可以参见  http://code.google.com/p/concurrentlinkedhashmap*/private static void test002() {ConcurrentLinkedHashMap<Integer, Integer> map = new ConcurrentLinkedHashMap.Builder<Integer, Integer>().maximumWeightedCapacity(2).weigher(Weighers.singleton()).build();map.put(1, 1);map.put(2, 2);map.put(3, 3);System.out.println(map.get(1));// null 已经失效了System.out.println(map.get(2));}}


0 0
原创粉丝点击