固定长度的Map(采用LRU策略)的实现
2019-02-14 本文已影响4人
zhglance
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
public class FixedCapacityMap {
protected static Map<Integer, Long> fixedCapacityCache = Collections.synchronizedMap(new LRUHashMap<>());
public static Long get(int key) {
return fixedCapacityCache.get(key);
}
public static void put(int key, long value) {
fixedCapacityCache.put(key, value);
}
public static int size() {
return fixedCapacityCache.size();
}
static class LRUHashMap<K, V> extends LinkedHashMap<K, V> {
private int capacity = 50;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
}