ru.yandex.clickhouse.util.LRUCache Maven / Gradle / Ivy
package ru.yandex.clickhouse.util;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
public class LRUCache extends LinkedHashMap {
/**
* Generated serial version UID.
*/
private static final long serialVersionUID = -4987484334796469814L;
private final int capacity;
private final Function loader;
public static Map create(int cacheSize, Function loader) {
return Collections.synchronizedMap(new LRUCache<>(cacheSize, loader));
}
protected LRUCache(int cacheSize, Function loader) {
super(cacheSize, 0.75f, true);
this.capacity = cacheSize;
this.loader = Objects.requireNonNull(loader);
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
@Override
public V get(Object key) {
@SuppressWarnings("unchecked")
K k = (K) Objects.requireNonNull(key);
V value = super.get(k);
if (value == null) {
value = loader.apply(k);
this.put(k, value);
}
return value;
}
}