com.clickhouse.data.cache.JdkLruCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of clickhouse-data Show documentation
Show all versions of clickhouse-data Show documentation
Data processing utilities for ClickHouse
package com.clickhouse.data.cache;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import com.clickhouse.data.ClickHouseCache;
/**
* A simple thread-safe LRU cache based on LinkedHashMap. It's not as effient as
* the one in Caffeine/Guava, but it requires no extra dependency.
*/
public class JdkLruCache implements ClickHouseCache {
static class LruCacheMap extends LinkedHashMap {
private final int capacity;
protected LruCacheMap(int capacity) {
super(capacity, 0.75f, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
}
/**
* Creates a cache with given capacity and load function.
*
* @param type of the key
* @param type of the value
* @param capacity capacity
* @param loadFunc load function
* @return cache
*/
public static ClickHouseCache create(int capacity, Function loadFunc) {
return new JdkLruCache<>(new LruCacheMap<>(capacity), loadFunc);
}
private final Map cache;
private final Function loadFunc;
protected JdkLruCache(Map cache, Function loadFunc) {
if (cache == null || loadFunc == null) {
throw new IllegalArgumentException("Non-null cache and load function are required");
}
this.cache = Collections.synchronizedMap(cache);
this.loadFunc = loadFunc;
}
@Override
public V get(K key) {
return cache.computeIfAbsent(key, loadFunc);
}
@Override
public T unwrap(Class clazz) {
return Objects.requireNonNull(clazz, "Non-null class is required").cast(cache);
}
}