ConcurrentLinkedHashMap 是Google团队提供的一个容器。它有什么用呢?其实它本身是对ConcurrentHashMap的封装,可以用来实现一个基于LRU策略的缓存。
LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,淘汰掉最不经常使用的数据。
我们在使用 ConcurrentLinkedHashMap 时,首先需要引入concurrentlinkedhashmap-lru,如下:
<!-- https://mvnrepository.com/artifact/com.googlecode.concurrentlinkedhashmap/concurrentlinkedhashmap-lru -->
<dependency>
<groupId>com.googlecode.concurrentlinkedhashmap</groupId>
<artifactId>concurrentlinkedhashmap-lru</artifactId>
<version>1.4.2</version>
</dependency>
首先我们来简单介绍下 ConcurrentLinkedHashMap 基本的用法
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.Weighers;
public class App {
public static void main(String[] args) {
ConcurrentLinkedHashMap<String, String> map = new ConcurrentLinkedHashMap.Builder<String, String>()
.maximumWeightedCapacity(3)
.weigher(Weighers.singleton())
.build();
map.put("1", "1");
map.put("2", "2");
map.put("3", "3");
map.put("4", "4");
map.forEach((k, v) -> System.out.println(k + ": " + v));
}
}
因为我们定义最大容量为 3 ,所以 ConcurrentLinkedHashMap 只能存储 3 个,当我们 put 第四个值时,我们最近最少使用的 1 就会被丢弃了。

这里我们可以验证一下,我们在 put 第四个值的时候,我们可以调用下第一个值,再次运行

这里我们发现我们在 ConcurrentLinkedHashMap 在把一个最近最少使用的值丢失时,是没有任何提示的,要是我们希望每丢弃一个值时,都可以有提示,该怎么做呢?


ConcurrentLinkedHashMap是Google提供的一种容器,作为ConcurrentHashMap的封装,适用于实现LRU缓存策略。当达到预设的最大容量时,它会淘汰最不常使用的数据。在使用中,我们可以设定最大容量,并且在超出容量时,旧值会被无提示地丢弃。若需要在丢弃值时得到通知,文章探讨了如何实现这一需求。
3881

被折叠的 条评论
为什么被折叠?



