简述
ConcurrentLinkedHashMap 是google团队提供的一个容器。它有什么用呢?其实它本身是对ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。详细介绍可以参见http://code.google.com/p/concurrentlinkedhashmap
使用范例
public static void main(String[] args) { |
ConcurrentLinkedHashMap<Integer, Integer> map = new |
ConcurrentLinkedHashMap.Builder<Integer,Integer>() |
.maximumWeightedCapacity(2). |
weigher(Weighers.singleton()).build(); |
System.out.println(map.get(1)); |
System.out.println(map.get(2)); |
ConcurrentLinkedHashMap 的构造函数比较特殊,它采用了Builder(构造器,GOF模式之一)。它本身也是实现了ConcurrentMap接口的,所以使用起来跟ConcurrentHashMap一样。我们先put进去三个元素,然后获取第一个元素,果然是null,因为基于LRU(最近使用)算法,key=1的节点已经失效了。
源代码解析
先来看看它的整体框架
架构-来自google code
它本质是额外维护了一个双向链表,每次读和写都要改变相应节点的位置,将其移至队列头。什么时候判断容易已经满了,是根据weight。每个元素都有一个weight,每增加一个元素,weight累计。当达到最大值的时候,就需要剔除最少操作的那个元素了,并且触发相关的事件。
我们先来看put函数
V put(K key, V value, boolean onlyIfAbsent) { |
final int weight = weigher.weightOf(key, value); |
final WeightedValue<V> weightedValue = new WeightedValue<V>(value, weight); |
final Node node = new Node(key, weightedValue); |
final Node prior = data.putIfAbsent(node.key, node); |
afterCompletion(new AddTask(node, weight)); |
} else if (onlyIfAbsent) { |
afterCompletion(new ReadTask(prior)); |
AddTask 是判断是否容量满了,需要剔除其他元素
final class AddTask extends AbstractTask { |
@GuardedBy("evictionLock") |
if (node.get().isAlive()) { |
while (hasOverflowed()) { |
Node node = evictionDeque.poll(); |
if (data.remove(node.key, node)) { |
pendingNotifications.add(node); |
get函数更简单一点,只是将这个key节点移至队列头
public V get(Object key) { |
final Node node = data.get(key); |
afterCompletion(new ReadTask(node)); |
性能比较 vs ConcurrentHashMap
不用说了,肯定是ConcurrentHashMap要好一点了,因为本文的主角还要维护一个操作队列嘛:)不过性能上不是差很多,见下图。

总结
利用ConcurrentLinkedHashMap来做基于LRU的缓存,还是值得推荐的。我们可以定义它的容器大小,基于LRU,就可以保证较高的命中率了。
参考资料:
http://code.google.com/p/concurrentlinkedhashmap