您的位置:首页 > 编程语言 > Java开发

Java高性能集合类 ConcurrentLinkedHashMap demo

2015-09-11 17:50 225 查看
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>() {

@Override
public 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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: