<dependency>
<groupId>com.googlecode.concurrentlinkedhashmap</groupId>
<artifactId>concurrentlinkedhashmap-lru</artifactId>
<version>1.4.2</version>
</dependency>
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.EntryWeigher;
import com.googlecode.concurrentlinkedhashmap.EvictionListener;
/**
* @author Cyberpunch
* @version $Id$
* @since 2021年09月22日 14:31
*/
public class LRUMap<T> {
private final LRUWeigher<T> lruWeigher;
private final ConcurrentLinkedHashMap<T, T> proxy;
public LRUMap() {
this.lruWeigher = new LRUWeigher<>();
this.proxy = new ConcurrentLinkedHashMap.Builder<T, T>().maximumWeightedCapacity(20).listener(lruWeigher).weigher(lruWeigher).build();
}
public T computeIfAbsent(T key, Function<? super T, ? extends T> mappingFunction) {
int increase = this.lruWeigher.increase(key);
System.out.println(key + " weigher " + increase);
return proxy.computeIfAbsent(key, mappingFunction);
}
public T putIfAbsent(T key, T value) {
int increase = this.lruWeigher.increase(key);
System.out.println(key + " weigher " + increase);
return proxy.putIfAbsent(key, value);
}
public int size() {
return proxy.size();
}
public T get(T key) {
return proxy.get(key);
}
static class LRUWeigher<T> implements EntryWeigher<T, T>, EvictionListener<T, T> {
private final ConcurrentHashMap<T, Integer> weigher = new ConcurrentHashMap<>();
public int increase(T key) {
int orDefault = weigher.computeIfAbsent(key, k -> 1);
weigher.replace(key, orDefault + 1);
return orDefault;
}
@Override
public void onEviction(T key, T value) {
System.out.println("del weigher " + key);
weigher.remove(key);
}
@Override
public int weightOf(T key, T value) {
return weigher.getOrDefault(key, 1);
}
}
}
import org.junit.Test;
/**
* @author Cyberpunch
* @version $Id$
* @since 2021年09月22日 11:21
*/
public class CacheTest {
@Test
public void LRUTest() {
LRUMap<Object> map = new LRUMap<>();
String key = "taiyi01";
String key2 = "taiyi02";
for (int i = 0; i < 200; i++) {
map.putIfAbsent("" + i, "" + i);
if (i % 2 == 0) {
map.putIfAbsent(key, key);
}
if (i % 10 == 0) {
map.putIfAbsent(key2, key2);
}
}
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
for (int i = 0; i < 100; i++) {
map.get(key);
}
System.out.println(map.size());
System.out.println(map.get(key));
System.out.println(map.get(key2));
}
}