All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.clickhouse.data.cache.CaffeineCache Maven / Gradle / Ivy

The newest version!
package com.clickhouse.data.cache;

import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import com.clickhouse.data.ClickHouseCache;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

/**
 * Cache based on Caffeine implementation. Please be aware that it's not really
 * a LRU cache.
 */
public class CaffeineCache implements ClickHouseCache {
    private final Cache cache;
    private final Function loadFunc;

    /**
     * Creates a cache with given capacity, seconds to expire(after access), and
     * load function.
     *
     * @param            type of the key
     * @param            type of the value
     * @param capacity      capacity of the cache
     * @param expireSeconds seconds to expire after access
     * @param loadFunc      load function
     * @return cache
     */
    public static  ClickHouseCache create(int capacity, long expireSeconds, Function loadFunc) {
        return new CaffeineCache<>(capacity, expireSeconds, loadFunc);
    }

    protected CaffeineCache(int capacity, long expireSeconds, Function loadFunc) {
        this.cache = Caffeine.newBuilder().maximumSize(capacity).expireAfterAccess(expireSeconds, TimeUnit.SECONDS)
                .build();
        this.loadFunc = Objects.requireNonNull(loadFunc, "Non-null load function is required");
    }

    @Override
    public V get(K key) {
        return cache.get(key, loadFunc);
    }

    @Override
    public  T unwrap(Class clazz) {
        return Objects.requireNonNull(clazz, "Non-null class is required").cast(cache);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy